0

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?

2
  • 2
    CodeReview is probably a better network for such kind of questions. codereview.stackexchange.com Commented Jun 3, 2016 at 15:14
  • Optimise for what? Commented Jun 3, 2016 at 15:24

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

This is broad question.

You can create a function like this

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

and on requirement call this function as

hoverChild(n) where n =1,2,3....

Comments

0
$('.section li').hover(function(){
    var num = $(this).index();
    $('.section2 li:nth-child('+num+')').toggleClass('is-over');
});

Comments

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.