Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery img added through append() triggers onload twice

The code that produces the headache for me is rather simple:

$(function(){ 
$("#test").append('<img onload="alert(\'hi\')" src="Image.jpg"/>');
})

I have the above code in my head and a div with id 'test' in the body. Now my problem is that the page produces two alerts when the image is loaded, but I expected it to produce only one as the 'onload' should be triggered only once- The way it happens when I add the image manually without any javascript..
See the fiddle I made at: http://jsfiddle.net/9985N/

Any help/explanation is greatly appreciated...

like image 569
Erric Avatar asked May 30 '12 12:05

Erric


1 Answers

UPDATED (Because some people don't believe me, lol)

Because .append creates the node first and then moves it to its appropriate position. Try appending the element first then adding its attributes as follow:

$(function() {
    $("#test").append(
        $("<img />").attr({
            src: "http://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/Bachalpseeflowers.jpg/300px-Bachalpseeflowers.jpg",
            onload: "alert(\'hi\')"
        })
    );
});

My answer does not "avoid" the problem, it answers it very directly. If you open the jQuery.js file in uncompressed format you can clearly see that .append creates the node on the document which is when the onload event is first called and then shifts it into position which is when it gets called again. Perhaps shift is the wrong word, forgive me as vocabulary is not my strong suit. However if you follow the code you see its creation and its movement, however the same is not said for using append again to move it, as the node is already created it simply moves from one element to another with no respark of onload. As I said, not sure best terminology, but it's very easy to follow along on the jQuery.js.

Don't believe me? Just tested the following fiddle in MSIE9, FF12, & GoogleChrome20 with 0 problems.

jsFiddle

just FYI, it's not really a horrible practice, but I see people write whole lines of HTML in jQuery all the time and that kind of defeats the purpose. It's a library with many books to read on purpose. Sometimes a complete line of HTML might seem easier, but it may not be faster as it doesn't follow all the great layout work that has been done for you. The idea is to "Write less, do more" and this includes HTML. After all, if you were gonna write the whole line of HTML, why use jQuery at all when you could just PHP it in!? :P Just a thought.

like image 200
SpYk3HH Avatar answered Sep 18 '22 00:09

SpYk3HH