Skip to content

Snippets

Jack Armley edited this page Jul 20, 2017 · 4 revisions

Toggle menu

// Create the toggleMenu function and store it in a variable
// called toggleMenu
var toggleMenu = function() {
	
  // Store reference to the button
  var button = document.querySelector('.site-menu-button');

  // Store reference to the menu
  var menu = document.querySelector('.site-menu');

  // Store the name of the open class we need
  var openClass = 'is-open';

  // Create an empty variable to use later,
  // so we can store when the menu has opened
  var menuIsOpen;

	// Do something every time the user clicks/taps the 
  // button
  button.addEventListener('click', function() {
        
    // Remember our empty variable from earlier?
		// We're now going to use it to check whether
		// the menu contains the class "is-open" 
		// (stored in the openClass variable)
    menuIsOpen = menu.classList.contains(openClass);

    // If menu is open, remove open class
		// else add open class
    if (menuIsOpen) {
      menu.classList.remove(openClass);
    } else {
      menu.classList.add(openClass);
    }
		
  });
};

// Run the toggleMenu function
toggleMenu();
Clone this wiki locally