Grab the real width of elements with jQuery

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


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.


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


$(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 *