Reputation: 18109
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 grateful.
Upvotes: 0
Views: 259
Reputation: 20105
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.
Upvotes: 1
Reputation: 171794
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.
Upvotes: 0