What is the best way to assign a percentage width based on a variable in jQuery?

Is there a way to assign a dynamic width value to an element?

Here is the code I am using:

    $(".menu_list_item").css({
        width: width + "%"
    });

Unfortunately, this doesn't appear to be functioning correctly.

If anyone has any suggestions or solutions, it would be greatly appreciated.

Answer №1

Here is a demonstration.

$(document).ready(function() {
  var length = "50%"

  $(".box").css({
    width: length
  });
});
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Title</title>
        <style>
            * {
                margin: 0px;
                height: 0px;
            }

            html, body, .container {
                width: 100%;
                height: 100%;
                background-color: red;
                display: flex;
                justify-content: center;
                align-items: center;
            }

            .box {
                height: 250px;
                background-color: orange;
            }
        </style>
        <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
        <script>
            $(document).ready(function() {
                var length = "25%"

                $(".box").css({
                    width: length
                });
            });
        </script>
    </head>
    <body>
        <div class="container">
            <div class="box">
            </div>
        </div>
    </body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating two variables that share an identical name

Can variables with the same name set outside of a function be called within the function? var a = $(window).width(); // This is the variable I want to call if(!$.isFunction(p)){ var a = $(window).height(); // Not this one alert(a); } FIDDLE ...

Modify the appearance of the username in the header after logging in with Yii

As a fellow coder using Yii, I'm seeking assistance in changing the style of my username displayed in the header upon login. Currently, it's appearing in black color and I desire it to be italicized-white. The code snippet below shows my header s ...

Unable to Scroll HTML Division

At the moment, I am working on a new website. I have a div where I place images and overlay text on them to describe the images. The issue I am facing is that the text does not scroll even though the scroll bar is visible. This is my HTML: <!DOCTY ...

Using regular expressions to eliminate text located outside of the tags within a string

Presented is a string consisting of an XML string below: var xmlString = "<str>rvrv</str>rvrv<q1>vrvv</q1>vrvrv<q2>rtvrvr</q2>"; I am seeking assistance on how to eliminate text that lies outside the tags (text no ...

A guide on obtaining the date format according to locale using Intl.DateTimeFormat within JavaScript

Can someone assist me in obtaining the standard date format (such as MM/DD/YYYY) based on a specified local id? The code snippet provided below is not returning the desired format. Any guidance on how to achieve this would be greatly appreciated. var da ...

Enable the duplication of strings within an array

Below is the HTML code snippet I am working with: <div class="col-sm-8"> <div class="row col-sm-12 pull-right paddingDiv"> <div class="col-sm-12"> <div class="marginBottom pull-right"> <bu ...

Unable to interpret data from the API

{ id: 8, customerName: "xyz", customerMobileNumber: "123456789", customerBillingAddress: "xyz address", customerShippingAddress: "xyz address", customerProductPurchasedDate: "2021-11-09T09:07:00.000Z", cust ...

Attempting to include a select element via transclusion

Looking to develop a custom directive named select that will replace a select element with a customized dropdown interface. For a clear example, check out this jsfiddle where the concept is demonstrated. Let's consider the below select element: < ...

Switch images when hovering

I currently have two dropdown menus called NEW and SHOP. When I hover over the New Menu 1, it should display the corresponding image. Similarly, when hovering over New Menu 2, the related image should be shown in a div with the ".menu-viewer" class. Whil ...

Retrieve a file from a remote server without storing it locally on the server

I need to download a zip file from another server without saving it locally. Currently, I am sending a POST request to the server which responds with the zip file, then I save it on my local server and send it using res.download. What I would like is to di ...

Explore the functionality of the Enter key and search button with JavaScript

I have the following code that works perfectly when I click on the search button. However, I would like to know how I can also initiate a search using the enter key. Here is the code snippet: <script> function mySearch() { var text = document.g ...

Unable to trigger $(this).find("a").click(); with JQuery

I have a simple query that I believe the jQuery experts can help me with. I am attempting to implement a functionality for performing an action on gridview row double click, following the instructions on . I have managed to redirect to another page succes ...

I am having an issue with my jQuery form submission not sending any POST variables

My code seems to be having issues as the PHP file is not receiving the POST-variables. I am unsure of what could be going wrong, so I am reaching out for some guidance. Here is the HTML: <div id="preloader" class="preload"></div> <div id=" ...

In JavaScript, you can update the class named "active" to become the active attribute for a link

My current menu uses superfish, but it lacks an active class to highlight the current page tab. To rectify this, I implemented the following JavaScript code. <script type="text/javascript"> var path = window.location.pathname.split('/'); p ...

Do you want your image to appear visually pleasing on all screen sizes?

Currently, I am working on a mobile website and encountering an issue with the image banner. For tablets, it should look like this: However, when viewed on mobile, it needs to appear as follows: This is the code I have implemented so far: <div class ...

Guide to creating a custom wrapper for a Material UI component with React JS

I am utilizing the Material UI next library for my project and currently working with the List component. Due to the beta version of the library, some parameter names are subject to change. To prevent any future issues, I have decided to create a wrapper a ...

Concealing a button within a specific interface

I am currently facing an issue with a data table that includes two control buttons: edit and save. My problem lies in hiding the save button on the initial preview. Basically, what I want to achieve is displaying only the Edit button on the first page. Wh ...

Create an HTML table with a line separating two table cells

I need help with creating a table row and td's dynamically using basic HTML and CSS. I would like to draw lines between the td's similar to the example image shown below. Can someone please assist me in achieving this? https://i.sstatic.net/GPd ...

Change the size of the individual cells within JointJS

I have some code for a jointjs demo that includes basic shapes on a paper. I am looking to adjust the size of the shapes or highlight them when clicked on or when the cursor moves over them. var graph = new joint.dia.Graph; v ...

Adding text in CKEditor with Angular while preserving the existing formatting

To add my merge field text at the current selection, I use this code: editor.model.change(writer => { var position = editor.model.document.selection.getFirstPosition(); // trying to connect with the last node position.stickiness = 'toP ...