Question

I hope this isn't confusing. I have two lists:

<ul class="list_A">
  <li class="item_1"></li>
  <li class="item_2"></li>
  <li class="item_3"></li>
</ul>

<ul class="list_B">
  <li class="item_1"></li>
  <li class="item_2"></li>
  <li class="item_3"></li>
</ul>

What I'm trying to figure out is when I hover over one of the list items, I want to have the list item with the same class in the other list have the same 'active' class appended to it. Which is what I can do with the below code.

jQuery(document).ready(function($){
  $(".item_1").hover(function () {
    $(".item_1").toggleClass('active');
  });
  $(".item_2").hover(function () {
    $(".item_2").toggleClass('active');
  });
  $(".item_2").hover(function () {
    $(".item_2").toggleClass('active');
  });
});

However, how do I make it so I just have it find the appropriate class without having to duplicate the code for each and have it something like the below? The below doesn't work. :(

jQuery(document).ready(function ($) {
  var i = 0;
  i++;
  $(".item_" + i).hover(function () {
    $(".item_" + i).toggleClass('active');
  });
});
Was it helpful?

Solution

You need to use the mouseenter and the mouseleave events instead of hover, or else it will trigger every time you mouse moves over the element. And the toggle will trigger all the time.

This should work fine:

jQuery(document).ready(function() {
    jQuery('li').mouseenter(function() {
        jQuery('.'+this.classList[0]).addClass('active');
    }).mouseleave(function() {
        jQuery('.'+this.classList[0]).removeClass('active');
    });
});

Here's the FIDDLE

EDIT: If you want to apply this to only specific lists, add a common class to each ul and update the first selector, like jQuery('ul.myclass > li')

OTHER TIPS

You should use it like that :

jQuery(document).ready(function ($) {
    for ( var i = 1; i < 4; i++ ) {
        $(".item_" + i).hover(function () {
            $(".item_" + i).toggleClass('active');
        });
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top