Search code examples
javascriptjqueryjquery-load

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?


Solution

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