Pradyut Bhattacharya
Pradyut Bhattacharya

Reputation: 5748

jquery image load strange behaviour

I have a page which has a img holder with the html: -

<img src="someimage.jpeg" alt="image" class="show_image"/>

Now i m updating the image with jquery using the code...

$('.show_image').attr('src', 'anotherimage.jpeg');

now when the image gets loaded i want to run some code...

as image scaling and letting the user know image is loaded

i run this code to know the image is loaded...

 var inc = 0;
    $('.show_image').load(function() {
        inc++;
        console.log('image loaded '+inc);
    });

now on repeatedly updating the img src the above load function is showing a strange

behaviour and is being called the number of times the img src is updated...

take a look at the firebig logs at this page...(use the prev n next buttons above)

pradyut.dyndns.org/original_image.jsp#imgid=202

i think i have to run the code like this

if(inc==1) {
  //run code
}

Any help

Thanks

Upvotes: 1

Views: 645

Answers (2)

user113716
user113716

Reputation: 322492

Use jQuery's .one() method:

$('.show_image').one('load', function() {
    inc++;
    console.log('image loaded '+inc);
});

This removes the handler after the first time it runs.

Upvotes: 3

Guffa
Guffa

Reputation: 700342

Only bind the load event once on the image, not every time that you load a new image.

Alternatively, use the unbind method to unbind any previous load event before binding a new one.

Upvotes: 0

Related Questions