tugberk
tugberk

Reputation: 58434

jQuery image load - multiple finish function execution

I am loading an image and appending it into a img element inside the DOM with jQuery when an thumbnail is clicked. Here is the code which does that:

$("#holder a").click(function (e) {
    var $this = $(this);
    var $img = $("#picture-holder img");
    $img.attr("src", $this.attr("href")).load(function () {
        console.log("done..");
    });
    e.preventDefault();
});

The weird thing here is that when it is finished loading, it write one log as expected at the first time. But the second time, it does that twice the previous size (which is 2). The third time, it log it for 6 times.

I am not sure what is going on here. When I check how many img elements #picture-holder holds, it returns 1 after every operation.

Edit 1:

I changed the code as below and mentioned problem is gone but I am not sure if it is the right way:

$("#holder a").click(function (e) {
    var $img = $("#picture-holder img");
    var $_img = $img.clone();
    var _href = this.href;

    $_img.attr("src", _href).load(function () {
        console.log("done..");
        $img.attr("src", _href);
    });
    e.preventDefault();
});

Edit 2:

Also, I now realized that this consumes a lot of CPU on clients machine. I am doing something wrong but where?

Upvotes: 0

Views: 616

Answers (2)

xiaowl
xiaowl

Reputation: 5207

You should NOT bind the load() handler inside of the click method. Or, you can unbindthe load handler and bind it again. Like this: $e.unbind('load').load(function(){}) But be careful, unbind method remove ALL handlers registered with 'load'.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

It's because you're adding a new load() handler every time the image changes.

Upvotes: 4

Related Questions