-2

I'm pretty familiar with jquery but im trying to learn vanilla js. How would I go about converting this jquery snippet into vanilla JS?

(function($) {
  $(function() { // DOM Ready

    // Toggle navigation
    $('#nav-toggle').click(function() {
      this.classList.toggle("active");
      // If sidebar is visible:
      if ($('body').hasClass('show-nav')) {
        // Hide sidebar
        $('body').removeClass('show-nav');
      } else { // If sidebar is hidden:
        $('body').addClass('show-nav');
        // Display sidebar
      }
    });
  });
})(jQuery);
Phil
  • 157,677
  • 23
  • 242
  • 245
James G
  • 71
  • 5
  • document ready -> [DOMContentLoaded event](https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded). `$('#nav-toggle')` -> `document.getElementById()`. `.click` -> `addEventListener`. `hasClass` / `removeClass` / `addClass` -> [Element.classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) – Phil Feb 14 '18 at 22:57
  • 1
    What have you tried? If we do the work for you, how are you learning? Apparently you didn't learn anything the last time you asked a similar question: https://stackoverflow.com/questions/42592157/convert-animated-jquery-side-nav-to-vanilla-js – jmoerdyk Feb 14 '18 at 23:03
  • 1
    Possible duplicate of [Is there an easy way to convert jquery code to javascript?](https://stackoverflow.com/questions/978799/is-there-an-easy-way-to-convert-jquery-code-to-javascript) – Heretic Monkey Feb 14 '18 at 23:03

1 Answers1

1

This is the vanilla js version

document.addEventListener("DOMContentLoaded", function(event) {
    document.getElementById('nav-toggle').addEventListener('click', function() {
      this.classList.toggle("active");

      var body = document.querySelector('body');
      // If sidebar is visible:
      if (body.classList.contains('show-nav')) {
        // Hide sidebar
        body.classList.remove('show-nav');
      } else { // If sidebar is hidden:
        body.classList.add('show-nav');
        // Display sidebar
      }
    });
});

Resources

Ele
  • 33,468
  • 7
  • 37
  • 75