ms_nitrogen ms_nitrogen - 4 months ago 17
Javascript Question

Condensing identical functions

I am trying to write a bit of JavaScript to help condense this jQuery set of functions (numbered 1 through 7) ...

$('.project-1 img').hover(function() {
$('#id1').slideToggle();
});
$('.project-2 img').hover(function() {
$('#id2').slideToggle();
});
...
$('.project-7 img').hover(function() {
$('#id7').slideToggle();
});


I tried this following bit of code, but it only targets
#id7
with
slideToggle
...

for (i = 1; i <= 7; i++) {
var projectNum = '.project-' + i + ' img';
var idNum = '#id' + i;
$(projectNum).hover(function() {
$(idNum).slideToggle();
});
};


How do I condense the code into something cleaner? Thanks!

Answer

Commenters above have correctly diagnosed the problem. Here's a fix:

for (i = 1; i <= 7; i++) {
  (function (i) {
    $('.project-' + i + ' img').hover(function () {
      $('#id' + i).slideToggle();
    });
  })(i);
};
Comments