What causes jQuery's .width() method to switch from returning the CSS-set percentage to the pixel width after a window resize?

After exhaustively console logging my code, I have finally identified the issue:

I am attempting to determine the pixel width of some nested divs, and everywhere I look suggests that jQuery's .width() method should solve the problem. The complication arises when, upon page refresh, it returns the percentage value of the div width (as defined in the CSS). However, after triggering the window resize event, .width() begins returning the pixel width!

Here is a simplified version of my HTML:

<div id="hud">
    <div class="character-position active" id="character-position-1" data-character-name="Character 1">
        <div class="character-tag" data-position="left">
        </div>
    </div>
    <div class="character-position active" id="character-position-2" data-character-name="Character 2">
        <div class="character-tag" data-position="right">
        </div>
    </div>
</div>

The relevant CSS:

#hud {
    position: relative;
    width: 100%;
}

.character-position {
    position: absolute;
    width: 65%;
}

#character-position-1 {
    left: 0%
}

#character-position-2 {
    left: 39%
}

.character-tag {
    position: absolute;
    width: 22%;
}

And the JavaScript (all within the jQuery ready function):

$(window).resize(resizeLocationComponent);

function resizeLocationComponent() {
        var windowWidth = $(window).width();
        $('#hud').css('height', ((windowWidth - 8) * 0.5625) + 'px');
        positionHudElements();
    }

positionHudElements = function() {
            var windowWidth = $(window).width();
            $characterPositions = $('.character-position.active');
            $.each($characterPositions, function(index) {
                var $tag = $(this).find('.character-tag');

                console.log("character position of "+$(this).attr('data-character-name')+" = "+$(this).css('left')+", "+$(this).css('top'));
                var percentX = parseInt($(this).css('left').replace('%', ''));
                var percentY = parseInt($(this).css('top').replace('%', ''));
                var windowHeight = windowWidth * 0.5625;
                var positionX = (percentX * windowWidth) / 100;
                var positionY = (percentY * windowHeight) / 100;
                var positionWidth = $(this).width();
                var tagWidth = $tag.width();
                var headSideOffset = parseInt(positionWidth * 0.35);
                console.log("windowWidth = "+windowWidth);
                console.log("character position of "+$(this).attr('data-character-name')+" = "+positionX+", "+positionY);

                console.log("characterPosition.width() = "+positionWidth);
                console.log("headSideOffset = "+headSideOffset);
                console.log("$tag.width() = "+tagWidth);
                var xOffset = 0;
                if ($tag.attr('data-position')=="left") {
                    xOffset = headSideOffset - tagWidth;
                    $tag.css('left', xOffset+'px');
                } else {
                    xOffset = headSideOffset - tagWidth;
                    $tag.css('right', xOffset+'px');
                }
                console.log("xOffset = "+xOffset);
            });

    }

The positionHudElements function is invoked on page load as well so the issue is not that it does not get called until the resize event. I can see where the function is called in my code and I observe the console logs from the positionHudElements function when the page is refreshed.

Any thoughts on why .width() would return CSS percentages before window resize and then switch to pixel widths afterward?

Thank you.

Answer №1

Take a look at this code:

 function adjustLocationComponentSize() {
        var windowWidth = $(window).width();
      // $('#hud).css('height', ((windowWidth - 8) * 0.5625) + 'px');  Oops, you forgot an inverted comma 
         $('#hud').css('height', ((windowWidth - 8) * 0.5625) + 'px');
        positionHudElements();
    }

You should use

$('#hud').css('height', ((windowWidth - 8) * 0.5625) + 'px');

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

How to centrally align tabs in Material-UI AppBar using ReactJS

I'm developing a React Application using Material-UI and facing difficulty in centering the 3 tabs within the blue AppBar. Currently, they are aligned to the left like this: (unable to embed images at the moment, apologies) This is the code snippet ...

Unfortunately, the datepicker feature does not seem to work properly on elements that have been dynamically added through the

My code progress so far is as follows: $('body').on('change', '.dropdown', function() { $.ajax({ success: function(res) { if(res.success == true) { return elements that have the class ...

Locate all the properties that are empty within each object contained in a JavaScript array

Consider this scenario: if I were to have an array of JavaScript objects like the following: var jsObjects = [ {a: 1, b: 2, c: null, d: 3, e: null}, {a: 3, b: null, c: null, d: 5, e: null}, {a: null, b: 6, c: null, d: 3, e: null}, {a: null, ...

What is the best way to retrieve the ID of the list item that has been clicked during a button event?

How can I use jQuery to get the ID of a selected list item when clicking a button in my HTML code? <ul id="nav"> <li><a href="#" rel="css/default.css" id="default" > <div class="r1"></div> </a>< ...

JSON and autocomplete feature causing performance problems

Developing an application that functions both online and offline using technologies like application cache and local storage is my current project. Utilizing jQuery mobile along with a jqm autocomplete solution from , I aim to create a seamless user experi ...

Is it possible to set up a universal type definition in TypeScript version 2 and above?

I have a collection of straightforward .ts files, not part of any projects but standalone .ts scripts. They implement certain node.js features. Both TypeScript and node type definitions are set up through the following commands: npm install -g typescript ...

The file_get_contents() function encountered an issue as the content type was not specified, leading to it assuming

I am currently working on a project using PHP and JavaScript. I need to call an API from the camera using PHP code. I am using the file_get_contents function and Post request for this purpose. Below is the code snippet: $value = $_POST['TakeNewPic&ap ...

Having trouble understanding how to receive a response from an AJAX request

Here is the code that I am having an issue with: render() { var urlstr : string = 'http://localhost:8081/dashboard2/sustain-master/resources/data/search_energy_performance_by_region.php'; urlstr = urlstr + "?division=sdsdfdsf"; urlst ...

Utilizing a loop for setting variable values in JavaScript

Using both JavaScript and JQuery. Let's imagine there is an array called ListArray with various sentences inside. Sounds easy enough. Is there a way to achieve this? var List = for (var i = 0; i < 10; i++) { //iterate over an array here to c ...

Button from Material-UI vanishes upon being clicked

I encountered an issue with a button that disappears when clicked on. Additionally, clicking the button once does not trigger any actions associated with it. In order to execute the button actions, I have to click the area where the button was located afte ...

Substitute the Iframe element with Ajax technology

Currently, I am working on a project where I want to include previews of various websites within my own website. Right now, I am using Iframes to load the website previews and allow users to interact with them. For SEO purposes, I have decided to replace ...

Remove the click event once the sorting process has been completed

I am currently working on a project that involves creating a list of sortable images using jquery sortable. Users can easily drag and drop the images for sorting purposes. Additionally, each image's parent anchor has a click event attached to open it ...

Incorporating a hyperlink into an Iframe triggered by Fancybox2-AJAX, specific to the Iframe's unique identifier

One thing I have noticed is that everything seems to be working fine up until the point where I try to load it through fancybox via AJAX. An example of it working statically: <iframe id="videourl1" width="640" height="340" src="" frameBorder="0">& ...

In Angular components, data cannot be updated without refreshing the page when using setInterval()

Here's the Angular component I'm working with: export class UserListComponent implements OnInit, OnDestroy { private _subscriptions: Subscription; private _users: User[] = []; private _clickableUser: boolean = true; constructor( priv ...

Tips for preserving drop down selections when refreshing the page

I am currently working on a program with 2 drop-down menus and 2 buttons. My goal is to have the first button disabled and second enabled when both dropdowns are selected and the "start" button is clicked. Additionally, I want the dropdowns to be disabled ...

Building Your Initial HTTP Server using Node.js

Hey everyone, I'm relatively new to node.js but have made some progress. Following the steps in this tutorial, I was able to create my first "example" server. However, there are a few things that I don't quite understand. Could someone please exp ...

How can I prevent receiving redundant data and effectively manage my data?

I am currently working on adding offline support to my app. The logic I am following is to first check if there is cached feed data available. If the data is present, it will set the feeds to that cached data and display it from the cache. However, it will ...

Choose all the alternative A radio buttons utilizing JavaScript

If the "4 stars" option is selected at the top, I want all corresponding "4 stars" options in the form to be automatically selected. Similarly, if "3 stars" is chosen, I need all the "3 stars" options to be selected. I attempted to achieve this functionali ...

Maximizing Bootstrap's Potential: Achieving Right Alignment for Divs

I am facing a challenge with aligning my div in the layout_cshtml. Currently, it is aligned to the left and the search bar and dropdownlist are not displaying properly. This negatively impacts the user experience. Additionally, my navigation menu is not ...

carousel/slider must be accessible

I have been searching for hours and still cannot find the perfect carousel/slider that I need. The one at this link is close to what I want, but it becomes inaccessible when JavaScript is disabled in the browser. I am looking for a jquery infinite carous ...