waynejames waynejames - 6 months ago 9
Javascript Question

Display links in side menu when main nav links are hovered

I'll try to explain this as best I can, I've had a search but nothing quite does what I want. I want to show links in the side menu, depending on what link is hovered/clicked in the main (top) nav, and display them until another link is hovered/clicked. Make sense? Here's what I have just so you can get an idea:

HTML:

<ul class="nav navbar-nav">
<li class="nav"><a class="toggle" href="#">LINK 1</a></li>
<li class="nav"><a class="toggle" href="#">LINK 2</a></li>
<li class="nav"><a class="toggle" href="#">LINK 3</a></li>
<li class="nav"><a class="toggle" href="#">LINK 4</a></li>
<li class="nav"><a class="toggle" href="#">LINK 5</a></li>
<li class="nav"><a class="toggle" href="#">LINK 6</a></li>
</ul>

<div class="sideMenu">
<div id="sideMenuLinks">
<ul id="menuContent" class="menuContent collapse out">
<li><a href="#">SM LINK 1</a></li>
<li><a href="#">SM LINK 2</a></li>
<li><a href="#">SM LINK 3</a></li>
<li><a href="#">SM LINK 4</a></li>
<li><a href="#">SM LINK 5</a></li>
<li><a href="#">SM LINK 6</a></li>
</ul>
</div>
</div>


jQuery:

$(document).ready(function() {
$('.toggle').hover(function () {
$('#sideMenuLinks').show('slow');
});
});


This works to just display on hover but obviously only for "sideMenuLinks", I have more links in different ID's, so if I hovered on "LINK 2" those links would be replaced and so on, any ideas? either jQuery or CSS would be fine.

Thanks in advance!

Answer

I would add a data-* attribute to the main navigation links like so:

<ul class="nav navbar-nav">
  <li class="nav"><a class="toggle" data-menu="first" href="#">LINK 1</a></li>
  <li class="nav"><a class="toggle" data-menu="second" href="#">LINK 2</a></li>
  <li class="nav"><a class="toggle" data-menu="third" href="#">LINK 3</a></li>
</ul>

<div class="sideMenu">
    <div id="sideMenuLinks">
        <ul id="first" class="menuContent collapse out">
          <li><a href="#">SM LINK 1</a></li>
          <li><a href="#">SM LINK 2</a></li>
        </ul>
        <ul id="second" class="menuContent collapse out">
          <li><a href="#">SM LINK 1</a></li>
          <li><a href="#">SM LINK 2</a></li>
        </ul>
        <ul id="third" class="menuContent collapse out">
          <li><a href="#">SM LINK 1</a></li>
          <li><a href="#">SM LINK 2</a></li>
        </ul>
     </div>
</div>

Then you could get the data-menu value when hovering:

$(".toggle").hover(function() {
    $(".menuContent").each(function() {
        $(this).hide();
    });
    var menu = $(this).attr("data-menu");
    $('#' + menu).show('slow');
});

Haven't tested this, but this could eventualy make the menus a little bit more dynamic.

Comments