0

I have a function that displays a different image each time it is called.

function Trial() {
    curTrial = increase(curTrial);

  //generate the html code
   $('#right_wrapper').append(`
    <div id="image_holder">
        <img id="image">
    </div>`)

    // present the image 
    var targetImage = document.getElementById('image')
    targetImage.src =  stimuli[curTrial];

    console.log(targetImage.onload = targetImage.height)

The way i though onload works is that it will not trigger until the src is loaded, but it seems to trigger anyway, and thus result the 0 height for the unloaded image. I've found more threads with similar issues, but none of those I've seen work with template literals.

How can i be sure that targetImage.height always returns the height for the loaded image, instead of 0?

Mitchell van Zuylen
  • 3,905
  • 4
  • 27
  • 64
  • It should be `targetImage.onload`, not `targetImage.src.onload`, shouldn't it? And `onload` should be a function, so I'm not sure you can set it to `height`. – Rik Lewis Feb 28 '17 at 12:22
  • I've tried it directly on `targetImage` and on `targetImage.src` which did not seem to make a difference. On the second point, i got that [from here](http://stackoverflow.com/questions/2485244/window-onload-seems-to-trigger-before-the-dom-is-loaded-javascript) – Mitchell van Zuylen Feb 28 '17 at 12:24
  • Well it should definitely be on the image, not a string attribute of the image. You'd be better registering events instead of using an `onload` attribute as well. And you should register it before setting the `src`, otherwise the image might have already loaded, and `onload` won't fire if it's already loaded. And that other page does not include a suggestion to set a function to a numeric, as this doesn't make any sense either. – Rik Lewis Feb 28 '17 at 12:27

0 Answers0