1

I have a script that looks like this:

$(function(){
    var backgroundImg = document.querySelector(".image-selector");

    var bmyObject = {
        backImgNaturalWidth : backgroundImg.naturalWidth,
        /*
            Rest of the object that is okay
        */
    };

    /*Rest of my script*/
}

The issue is that sometimes naturalwidth is taken properly and sometimes it is 0 which breaks rest of the script that makes calculations with this number involved. Any ideas why this happens or how to solve would be great.

MWiesner
  • 8,868
  • 11
  • 36
  • 70
Mindaugas
  • 1,173
  • 5
  • 15
  • 31
  • 2
    I'd assume the image hasn't loaded if you're getting 0. Document ready, which you do use in the code above, doesn't include images - just the DOM. – Reinstate Monica Cellio Nov 05 '15 at 15:47
  • 1
    Like said above, so use instead `$(window).on('load', function(){...});` – A. Wolff Nov 05 '15 at 15:51
  • duplicate http://stackoverflow.com/questions/1645166/image-naturalwidth-return-zero – Ramanlfc Nov 05 '15 at 15:52
  • Thanks guys, yea - I just had DOM ready, when I needed to use $(window).load() to get access to images as well. Thanks for help. Ramanlfc - not really duplicate(goal is the same, but issue and solution path are different). :) – Mindaugas Nov 05 '15 at 15:59

1 Answers1

0

for those who will come by searching for an answer to this question: instead of document ready you need to listen to window load as document ready fires when DOM is ready while window load fires when DOM, images and etc. are ready. So modified code would look like this:

$(window).load(function(){
    var backgroundImg = document.querySelector(".image-selector");

    var bmyObject = {
        backImgNaturalWidth : backgroundImg.naturalWidth,
        /*
            Rest of the object that is okay
        */
    };

    /*Rest of my script*/
});
Mindaugas
  • 1,173
  • 5
  • 15
  • 31