Is jquery width () incorrect right after the document is ready?

For some reason, $("...").width() returns the wrong value immediately after the document is ready.

I see these values:

Immediately after the document is ready:

 $(document).ready(function(){ $("li.active a").width() //returns 76 - incorrect }); $(document).ready(function(){ $(window).load(function(){ $("li.active a").width() //returns 59 - the correct value }); }); $(document).ready(function(){ setTimeout(function(){ $("li.active a").width() //returns 59 - the correct value }, 100); }); 

I get the width of the Wordpress menu items and resize them so that they always fit my responsive design. There are no images or assets that could cause this change.

Update See my comment below. Turns out there was an asset, a built-in font that took a split second to load.

+7
source share
1 answer

This may be due to the lack of $(window).load in the first example.

"The document ready event is already fired when the HTML document and the DOM are ready, even if all the graphic files are still loaded. If you want to connect your events to certain elements before the window is loaded, then $ (document) .ready is the right place." *

 $(document).ready(function() { // executes when HTML-Document is loaded and DOM is ready alert("document is ready"); }); 

"Event runs later when the full page is fully loaded, including all frames, objects, and images. Therefore, functions that relate to images or other page content in the load event for the window or the content tag itself. "*

 $(window).load(function() { // executes when complete page is fully loaded (all frames, objects and images) alert("window is loaded"); }); 

* Quotes obtained from 4loc .

+15
source

All Articles