Blog>
Snippets

Toggle Element Visibility

Use `querySelector` to toggle visibility of a `.hidden` class element on clicking a `Show/Hide` button.
// Handler function to toggle visibility of the element
function toggleVisibility() {
  // Use querySelector to select the first element with the class 'hidden'
  var hiddenElement = document.querySelector('.hidden');
  
  // Check if the element is currently visible by checking its display style
  if (hiddenElement.style.display === 'none') {
    // If the element is hidden, change the display to 'block' to show it
    hiddenElement.style.display = 'block';
  } else {
    // If the element is shown, change the display to 'none' to hide it
    hiddenElement.style.display = 'none';
  }
}

// Use querySelector to select the 'Show/Hide' button
var showHideButton = document.querySelector('button');

// Add click event listener to the 'Show/Hide' button
// When the button is clicked, the toggleVisibility function will be executed
showHideButton.addEventListener('click', toggleVisibility);
The code defines a function 'toggleVisibility' that toggles the display style between 'none' and 'block' for the first element with the class 'hidden'. It then selects the 'Show/Hide' button and adds an event listener for the 'click' event to execute the 'toggleVisibility' function, thereby toggling the element's visibility.