Skip to content Skip to sidebar Skip to footer

JQuery .load On Image Fires Once

Context A user page with HR information. I have a menu under the user picture which has an unfixed size. I update the menu margin-top when the picture is loaded: _setMenuMarginTop:

Solution 1:

How about triggering the onload handler again ?

_setMenuMarginTop: function () {
    var that = this;

    $('#picture > img').on('load', function () {
        that.$el.css('margin-top', $(this).height() + 'px');
    }).each(function() {
         if (this.complete) $(this).trigger('load');
    });
}

And note that's it's an event handler, calling the function again just applies another event handler.


Solution 2:

This happens because the new image doesn't have the load function on it. Replacing the image breaks the event. You can use the jQuery on function to always fire the event on all images that are in the #picture div:

$('#picture').on('load', 'img', function() {
    that.$el.css('margin-top', $(this).height() + 'px');
})

That should do it. This would replace your $('#picture > img').load(function () { line

What this does is attach the event to the '#picture' div, but actually fire when an 'img' inside the #picture div is loaded.

This way, if the picture is removed, the event isn't removed as well.


Solution 3:

I believe assigned image src should be different each time for load to fire. Consider following demo: http://jsfiddle.net/j4tP8/1/

I am using basic image and button

<button id="one">One</button>
<img id="img" />

Which connected via

$('#one').click(function() {
    $('#img').attr('src','https://site/image.jpg')
})

$('#img').load(function() {
    alert('loaded');
})

When you click the button - image is assigned source. As it is load event will fire only once. But f you modify the code by adding random string to the source:

$('#one').click(function() {
    $('#img').attr('src','https://site/image.jpg?' + Math.random() )
})

load will fire every time.


Post a Comment for "JQuery .load On Image Fires Once"