JAVASCRIPT

Toggle CSS Classes to Show/Hide Elements

Control element visibility and apply styles using JavaScript by efficiently toggling CSS classes. This is fundamental for interactive UI components like menus or modals.

const toggleButton = document.getElementById('toggleButton');
const infoBox = document.getElementById('infoBox');

if (toggleButton && infoBox) {
    toggleButton.addEventListener('click', function() {
        // Toggles the 'hidden' class on the infoBox element
        infoBox.classList.toggle('hidden');

        // Optional: Toggle a different class for styling based on state
        // infoBox.classList.toggle('active');

        // You can also check if the class exists after toggling
        if (infoBox.classList.contains('hidden')) {
            console.log('Info box is now hidden.');
        } else {
            console.log('Info box is now visible.');
        }
    });
} else {
    console.error('Toggle button or info box element not found!');
}

// Example for setting/removing a class explicitly
const anotherElement = document.getElementById('anotherElement');
if (anotherElement) {
    // anotherElement.classList.add('highlight');
    // anotherElement.classList.remove('highlight');
}
How it works: This snippet demonstrates how to easily toggle the presence of a CSS class on an HTML element using `element.classList.toggle()`. This method is highly effective for managing UI state, such as showing or hiding elements, changing styles, or activating/deactivating components. By simply toggling a class, you can leverage predefined CSS rules to control an element's appearance without directly manipulating inline styles, leading to cleaner and more maintainable code.

Need help integrating this into your project?

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

Hire DigitalCodeLabs