2

Here's my code:

$('.tab_map1 area').hover(function(){
    $('#nav1').find('a').stop().toggleClass('hover', 500);
        return false;
});
$('.tab_map2 area').hover(function(){
    $('#nav2').find('a').stop().toggleClass('hover', 500);
        return false;
});
$('.tab_map3 area').hover(function(){
    $('#nav3').find('a').stop().toggleClass('hover', 500);
        return false;
});
$('.tab_map4 area').hover(function(){
    $('#nav4').find('a').stop().toggleClass('hover', 500);
        return false;
});

... (there's 8 of them)

I'd like to not repeat the same code multiple times but optimize it somehow. Is there a chance to replace .tab_map1-8 and #nav1-8 with some index value?

I tried:

var n = 8;
$('li.tab_map area').eq(n).hover(function(){
    $('#nav').eq(n).find('a').stop().toggleClass('hover', 500);
        return false;
});

and:

$("#navibar ul").each(function(index) {
$('.tab_map:eq(' + index + ') area').hover(function(index){
    $('#nav:eq(' + index + ')').find('a').stop().toggleClass('hover', 500);
        return false;
});
});

Both doesn't work.

1 Answer 1

2

The easiest way to do this is to use a for loop over the range 1-8. Then build up the selector for each index. For example

for (var i = 1; i <= 8; i++) {
  var helper = function (sel, id) {
    $(sel).hover(function() {
      $(id).find('a').stop().toggleClass('hover', 500);
      return false;
    });
  };

  helper('.tab_map' + i + ' area', '#nav' + i);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately it doesn't seems to work. I guess it's because of map/area - they are harder to handle. Here is live example how it should work: jsfiddle.net/LsAEu
@Annaccond my bad. I felt right into the javascript loop capture problem. Here is a fiddle that works. I'll update my answer jsfiddle.net/LsAEu

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.