1

I would like to condense the following jQuery code, as I'd like to account for future navigation items without having to adjust this jQuery code.

jQuery

$('.nav-1, .mega-menu-1').on('hover', function() {
  $('.mega-menu-1').toggleClass('slide');
});
$('.nav-2, .mega-menu-2').on('hover', function() {
  $('.mega-menu-2').toggleClass('slide');
});
$('.nav-3, .mega-menu-3').on('hover', function() {
  $('.mega-menu-3').toggleClass('slide');
});

HTML

<ul class="menu">
  <li class="nav-1"><a href="#">Item 1</a></li>
  <li class="nav-2"><a href="#">Item 2</a></li>
  <li class="nav-3"><a href="#">Item 3</a></li>
</ul>

<div class="mega-menu">
  <div class="mega-menu-1">Content 1</div>
  <div class="mega-menu-2">Content 2</div>
  <div class="mega-menu-3">Content 3</div>
</div>
Huangism
  • 16,278
  • 7
  • 48
  • 74
Weebs
  • 155
  • 2
  • 10
  • How are you getting the navigation items? If you return your navigation items as a list, you could iterate that list and append the iterator to your class names. if each navigation item does the exact same thing on the hover event, just give them all the same class. – Ryan Wilson Feb 05 '18 at 16:28
  • 2
    The technique is called 'Dont repeat yourself', or DRY. We need to see the HTML that's associated with this JS code in order to show you how to improve the logic. – Rory McCrossan Feb 05 '18 at 16:29
  • Possible duplicate of [Using 'starts with' selector on individual class names](https://stackoverflow.com/q/2178416/11683) – GSerg Feb 05 '18 at 16:30
  • Put the index as a data attribute so you can get the index on hover and do what you need – Huangism Feb 05 '18 at 16:32
  • The HTML structure of the menu has been added. – Weebs Feb 05 '18 at 16:38

1 Answers1

1

If you don't want to add index as data attributes then you could do this

I added menu-item class to all items so it can targeted with one class. .index() gets the index of the element and .eq(index) gives you the element at that index. I also updated the mega menu ul class so it does not conflict with the rest of the mega menu classes

In the future you can just add items without worrying about updating the index at all.

https://jsfiddle.net/2xr1gtLk/1/

<ul class="menu">
  <li class="nav menu-item"><a href="#">Item 1</a></li>
  <li class="nav menu-item"><a href="#">Item 2</a></li>
  <li class="nav menu-item"><a href="#">Item 3</a></li>
</ul>

<div class="mega-menu-container">
  <div class="mega-menu menu-item">Content 1</div>
  <div class="mega-menu menu-item">Content 2</div>
  <div class="mega-menu menu-item">Content 3</div>
</div>

JS

$('.menu-item').hover(function() {
    $('.mega-menu').eq( $(this).index() ).toggleClass('slide');
});
Huangism
  • 16,278
  • 7
  • 48
  • 74
  • Interesting solution, @Huangism! Thank you much for your time in constructing this solution for me, as it works beautifully. – Weebs Feb 05 '18 at 17:28