0

I have this Jquery code which is toggling mobile navigation, which is in two divs (left and right side of the logo, but logo is hidden):

$(document).ready(function() {
  $('.menu').on('click', function(e){
    $('.main-nav').toggleClass('active');
    e.preventDefault();
  });
});

I try to rewrite this to vannila js by this:

document.addEventListener('DOMContentLoaded', function() {
  var toggleNav = document.getElementsByClassName('main-nav');

  function myFunction() {
    for (var i=0; i<toggleNav.length; i++) {
      toggleNav[i].classList.toggle('active');
      console.log('myFunction() fired...');
      return false;
    }
  };

  var x = document.getElementsByClassName('menu')[0];
  x.addEventListener('click', myFunction);
});

But this is just only toggling the first nav in the loop, which is left-nav, like if I used var toggleNav = document.getElementsByClassName('main-nav')[0]; in the past. What went wrong?

HTML code:

<div class="toggle-mobile-nav">
  <a href="#" class="menu">Menu <span>≡</span></a>
</div>

<div class="navigation">

  <nav class="main-nav left-nav">
    ...
  </nav>

  <div class="logo logo-nav">
    <a href="/"><img class="logo-svg" src="..." alt="" /></a>
  </div>

  <nav class="main-nav right-nav">
    ...
  </nav>

</div>
Lanti
  • 2,299
  • 2
  • 36
  • 69

1 Answers1

3

You are returning false inside for loop, that will act like sort of a break,

function myFunction() {
    for (var i=0; i<toggleNav.length; i++) {
      toggleNav[i].classList.toggle('active');
      console.log('myFunction() fired...');
    }
  return false;
};

You have to return false in your function. That too after for loop's execution.

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • There are various other issues as well, feel free to copy anything relevant from my now-deleted answer. – T.J. Crowder Apr 03 '16 at 13:41
  • `var x = document.getElementsByClassName('menu')[0];` intentionally returning only the first element. Later on that button will have more unique classname which is never presented again in my code. I think this is faster request than looping through it? – Lanti Apr 03 '16 at 13:44
  • @TJ OP can be benefited from union of our 2 answers. I thought what I have explained here was the main issue for OP. Ok I Will explain the things that you said in your answer here. – Rajaprabhu Aravindasamy Apr 03 '16 at 13:44
  • Yep, this is the main issue! Thank You! I need one more minute to accept as the good answer. :) – Lanti Apr 03 '16 at 13:45
  • I think you're right, that's why I removed mine, knowing you could still see and integrate its points. :-) – T.J. Crowder Apr 03 '16 at 13:47