I am trying to write some very basic jQuery code here.
What I am doing here is I want the image to toggle when hover. I have 5 images, and I was able to archive that when I wrote 5 codes, 1 for each image.
$('#menu > ul:first-child > li:nth-child(1)').hover(function(){
$('li:nth-child(1) > .image-hover').toggle();
$('li:nth-child(1) > .image').toggle();
});
$('#menu > ul:first-child > li:nth-child(2)').hover(function(){
$('li:nth-child(2) > .image-hover').toggle();
$('li:nth-child(2) > .image').toggle();
});
$('#menu > ul:first-child > li:nth-child(3)').hover(function(){
$('li:nth-child(3) > .image-hover').toggle();
$('li:nth-child(3) > .image').toggle();
});
$('#menu > ul:first-child > li:nth-child(4)').hover(function(){
$('li:nth-child(4) > .image-hover').toggle();
$('li:nth-child(4) > .image').toggle();
});
$('#menu > ul:first-child > li:nth-child(5)').hover(function(){
$('li:nth-child(5) > .image-hover').toggle();
$('li:nth-child(5) > .image').toggle();
});
Now I want to shorten the code, using the "for" loop. The idea is I have a variable i, starting from 1, increasing 1 by 1 up to 5. The nth-child above, instead of having a specific number, will now hold i. As i changes, nth-child(i) will have respective values of i.
(function($){
for (var i = 1; i < 6; i++) {
$('#menu > ul:first-child > li:nth-child(i)').hover(function(){
$('li:nth-child(i) > .image-hover').toggle();
$('li:nth-child(i) > .image').toggle();
});
};
})(jQuery);
This shorten code doesn't work though.
Can someone help me with this? Thanks a lot.
ias a variable... still you have the problem described in developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…