jQuery .width() or .height() Always Returns 0 – Fix!

While working on a Sitefinity Image Gallery control, I came across an issue using jQuery.width() and height() methods on the loaded images from the Sitefinity Images & Documents module. For most of the images, both the returned values for width and height were returning 0. After loading different pieces from the DOM, I realized that most (if not all) of the images were not actually getting loaded into the DOM before trying to find the width and height.

The solution was to, instead of using document.ready(), use window.load().

Original, non-working solution used the document.ready() function as below:

<script type="text/javascript">
        $(document).ready(function () {
            $(".thumb img").each(function () {
	 $(this).load();
                var width = $(this).width();
		var height = $(this).height();
		$(this).css({ 'margin-left': '50%', 'margin-top': '50%' });
                            $(this).css({ 'left': '-' + ((width) / 2) + 'px', 'top': '-' + ((height) / 2) + 'px' });
            });
        });
    </script>

The fix and working solution is to use the window.load() function as below:

<script type="text/javascript">
        $(window).load(function () {
            $(".thumb img").each(function () {
		$(this).load();
                            var width = $(this).width();
		var height = $(this).height();
		$(this).css({ 'margin-left': '50%', 'margin-top': '50%' });
                            $(this).css({ 'left': '-' + ((width) / 2) + 'px', 'top': '-' + ((height) / 2) + 'px' });
            });
        });
    </script>
Posted in Image Manipulation, jQuery, Sitefinity
  • SeveN

    i owe you! lol

  • SpaceBeers

    Saved my life just now. I figured having the code in the footer would solve that but nope. Thanks

    • http://www.fortwaynewebdevelopment.com/ Brad Taylor

      Glad it helped! Thanks for commenting also, helps me know if more changes are in order! I spent quite a bit of time myself trying to figure out why this wasn’t working as well – placing the code in the footer was my first guess.

  • Tirameenlasbolas

    YOU RULE!  Thanks

  • http://www.facebook.com/profile.php?id=100000412246131 Janne Manne

    Fantastic. This solved a big big problem for me. Thanks a lot!

  • Agustin

    Didn’t work for me… :

  • http://www.corvusconceptions.com Erik Goens

    Many Thanks! Ran through this issue for way too long before finding your post.

About Fort Wayne Web Development
FortWayneWebDevelopment.com is specifically a web-development and design blog dedicated to providing answers for common issues, problems, bugs, and requests of popular web-based software, such as Magento eCommerce, Sitefinity CMS, MODx CMS. Alongside these pieces of software, this blog will also feature code snippets to specific programming languages, such as JavaScript (more specifically the jQuery libraries), ASP.Net with C#, PHP, HTML, and CSS.