JAVASCRIPT

Toggling Element Visibility Using CSS Classes

Discover how to efficiently show or hide DOM elements by dynamically adding or removing predefined CSS classes with JavaScript.

function toggleVisibility(elementId, hiddenClass = 'hidden') {
  const element = document.getElementById(elementId);
  if (element) {
    element.classList.toggle(hiddenClass);
    console.log(`Toggled visibility for '${elementId}'. Now ${element.classList.contains(hiddenClass) ? 'hidden' : 'visible'}.`);
  } else {
    console.error(`Element with ID '${elementId}' not found.`);
  }
}

// Assuming you have this CSS:
// .hidden {
//   display: none !important;
//   visibility: hidden;
//   opacity: 0;
//   transition: opacity 0.3s ease-in-out;
// }
// .my-box {
//   width: 100px; height: 100px; background-color: lightblue;
//   margin: 10px;
// }

// Example usage:
// <div id="myBox" class="my-box">Hello!</div>
// <button onclick="toggleVisibility('myBox')">Toggle Box</button>

// Initially hide the box after 2 seconds
setTimeout(() => toggleVisibility('myBox'), 2000);

// Toggle again after 4 seconds
setTimeout(() => toggleVisibility('myBox'), 4000);
How it works: This snippet demonstrates a clean way to toggle an element's visibility by manipulating its CSS classes. Instead of directly altering `element.style.display` or `element.style.visibility`, we define a CSS class (e.g., `.hidden`) that applies the desired hiding styles. The JavaScript function then uses `element.classList.toggle()` to add or remove this class, allowing CSS to manage the actual styling. This approach separates concerns, makes the code cleaner, and enables complex transitions or animations directly in CSS.

Need help integrating this into your project?

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

Hire DigitalCodeLabs