Grab the real width of elements with jQuery

This one took me about an hour to figure out so here goes…

Explanation…

Images don’t load into jQuery’s $(document).ready() function so you have to wait for the window to load. Then jQuery can get the image dimensions.

Wrong…

	$(document).ready(function() {
		var imageWidth = $("#image").width();
	});

Right…

$(window).load(function() {
		var imageWidth = $("#image").width();
	});

The difference is jQuery executing before the browser has time to load the images, so there’s dimensional information on images available. However, if you wait for the window to load, all the information you need becomes available.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.