JAVASCRIPT

Toggle Element Visibility and CSS Classes

Learn how to easily toggle the visibility of an HTML element and manage its CSS classes with JavaScript, enabling interactive UI elements.

<style>
  .hidden {
    display: none;
  }
  .box {
    width: 150px;
    height: 100px;
    background-color: #ffccbc;
    border: 2px solid #ff7043;
    margin-top: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: sans-serif;
  }
</style>

<button id="toggleBtn">Toggle Box</button>
<div id="myElement" class="box">I'm a toggled box!</div>

<script>
const toggleButton = document.getElementById('toggleBtn');
const targetElement = document.getElementById('myElement');

toggleButton.addEventListener('click', () => {
  targetElement.classList.toggle('hidden'); // Adds 'hidden' if not present, removes if present
  
  const isHidden = targetElement.classList.contains('hidden');
  console.log(`Element is now ${isHidden ? 'hidden' : 'visible'}.`);
});
</script>
How it works: This snippet demonstrates a common pattern for controlling element visibility and styling using JavaScript and CSS classes. An HTML button is set up to interact with a target `div`. When clicked, the `classList.toggle('hidden')` method is invoked. This method efficiently adds the `hidden` class to the element if it's not present, or removes it if it is. The `hidden` class, defined in CSS as `display: none;`, then handles the actual visual hiding or showing of the element. This approach is cleaner and more maintainable than directly manipulating `element.style.display`.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs