Pretty new to jquery and having a bit of a problem with a function I wrote, very similar to this problem, and if that's anything to go on then apparently I have a closure problem. As Peter Bailey put it in the above thread, this is what's happening:
- Iterate over some values
- Define/assign a function in that iteration that uses iterated variables
- You learn that every function uses only values from the last iteration.
- WTF?
This is my code:
var pages=['home', 'about', 'events', 'info', 'qa', 'photos', 'contact'];
for (i in pages) {
$link='"'+"[href$='gaction.php?page="+(pages[i])+"']"+'"';
$source="/images/"+(pages[i])+".png";
$($link).hoverIntent(function() {
$('#logo_text').stop(true, true).fadeOut(
0,
function() {
$('#logo_text').attr('src', $source).fadeIn('slow'); // swaps logo
});
}, function() {
$('#logo_text').stop(true, true).pause(300).fadeOut(
0,
function () {
$('#logo_text').attr('src', '/images/name.png').fadeIn('slow'); //swaps back
});
});
}
I know the $link definition is pretty messy, but that bit works.
The function's meant to replace the picture in #logo_text with one depending on the link that's hovered over, but by the end of it every link changes the picture to the 'contact' (last) one.
Didn't really understand how to fix it from the other thread so if someone can help out that would be great!