Grommit
Grommit

Reputation: 45

Jquery iteration for child elements

For a simple menu I'm using jQuery to fade in a specific h1 when a menu option is hovered. I could write the lines of code for each element, but I'd like to know how to write this more efficiently using iteration.

<ul class="menu_locations">
    <li><a>Option A</a></li>
    <li><a>Option B</a></li>
    <li><a>Option C</a></li>
    <li><a>Option D</a></li>
</ul>

<div class="menu_info">
    <h1>This is option A</h1>
    <h1>This is option B</h1>
    <h1>This is option C</h1>
    <h1>And finally we have D</h1>
</div>

This is what I thought it should look like in jQuery

$(".menu_locations").children().each().hover(
    function() {
        $("").fadeIn();
    }, function() {
        $("").fadeOut();
});

Upvotes: 0

Views: 53

Answers (1)

adeneo
adeneo

Reputation: 318352

There's no need for each, jQuery iterates internally
You could use the index to target the H1 with the same index, and stop will stop the animation when something else is hovered.

You could also use fadeToggle to fade both in and out in the same handler

$(".menu_locations li").hover(function() {
  $(".menu_info h1").eq( $(this).index() ).stop(true, true).fadeToggle();
});
.menu_info h1 {display:none; position: absolute}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu_locations">
    <li><a>Option A</a></li>
    <li><a>Option B</a></li>
    <li><a>Option C</a></li>
    <li><a>Option D</a></li>
</ul>

<div class="menu_info">
    <h1>This is option A</h1>
    <h1>This is option B</h1>
    <h1>This is option C</h1>
    <h1>And finally we have D</h1>
</div>

Upvotes: 4

Related Questions