tib tib - 6 months ago 9
jQuery Question

How to optimize Javascript function

I want to make an animation on a div child element when i hover the child of a different div this is my code:



$('.section li:nth-child(1)').hover(function(){
$('.section2 li:nth-child(1)').toggleClass('is-over');
});

$('.section li:nth-child(2)').hover(function(){
$('.section2 li:nth-child(2)').toggleClass('is-over');
});

$('.section li:nth-child(3)').hover(function(){
$('.section2 li:nth-child(3)').toggleClass('is-over');
});

$('.section li:nth-child(4)').hover(function(){
$('.section2 li:nth-child(4)').toggleClass('is-over');
});





So how can i optimize it?

Answer

You can use $(this).index() to get the index of hovered item

$('.section li').hover(function(){
  var index = $(this).index()+1;
  $('.section2 li:nth-child('+index+')').toggleClass('is-over');
});
.is-over {
  color : red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="section">
    <li>Step 1</li>
    <li>Step 2</li>
</ul>

<ul class="section2">
    <li>Step 11</li>
    <li>Step 22</li>
</ul>