views:

186

answers:

2

I've spent the last four hours trying to figure out why my jQuery events are firing multiple times for something that can only happen once. Basically, I have an ad banner that will be rotating images with jQuery. I'm waiting until the page loads to load all the images except for the one that is shown by default:

$("#mainadslot").prepend('<img>')
.find(":first-child")
.attr("src", src)
.load(function(event) {
    // Global javascript variable itterates here
    // to count how many images have loaded. 
    // If they're all done, we can start rotating
});

And I haven't even gotten to the effects yet, because for some odd reason the onLoad on the images is firing three times for each image. My first guess was bubbling, so I did a little poking around and tried the .stopPropagation() jQuery function. Unfortunately, that didn't do a thing for me.

If anyone could explain to me why this is happening, I would be so greatful.

A: 

Have you tried setting the load() event handler before the 'src' attribute?

$("#mainadslot").prepend('<img>')
.find(":first-child")
.load(function(event) {
    // Global javascript variable itterates here
    // to count how many images have loaded. 
    // If they're all done, we can start rotating
})
.attr("src", src);

According to the documentation: load will work only if you set it before the element has completely loaded.

Maybe that won't solve your problem, but it is something you should change anyway.

Philippe Leybaert
Yeah, that's actually how I originally had it set but then I considered that if there was no source, there would be no load time. So as soon as the <img> tag is added to the DOM, it is done loading. I'm still not certain about that, but either way, the image is large and the way I have it now the .load() event is being bound before the image is finished loading. Thanks for your input!
Bloudermilk
I set up a test case on jsbin, and the problem you're describing is not reproducable. The link is http://jsbin.com/ozihu . Are you sure you're not binding the load() event three times by accident?
Philippe Leybaert
+1  A: 

Does #mainadslot have more than one Element that can be considered a first-child beneath it?

Your find() expression will grab all first-children descendants of #mainadslot. So, if the markup looks like this (just a crazy example):

<div id="mainadslot">
    <div>
        <span>
            <img>
        </span>
    </div>
</div>

You'll have 3 first-children: the div, span, and img.

ajm
It would appear that my understanding of the jQuery :first-child selector was incorrect. Your hypothesis was indeed correct. Thank you!
Bloudermilk
I, too, was punched in the face by find() and filter() before. I feel your pain.
ajm