search ]

Toggling Classes using JavaScript & Data Attributes

In this post, we’ll explore how to toggle CSS classes on HTML elements using JavaScript and data attributes. This method is useful for creating interactive elements on your webpage without adding complex JavaScript logic.

Basic HTML Setup

First, let’s look at the basic HTML structure. We’ll use a button to toggle a class on a target element.

<button data-toggle-target="#content" data-toggle-class="highlight">Toggle Highlight</button>
<div id="content">This is the content to be toggled.</div>

JavaScript to Toggle Classes

Next, we’ll add JavaScript to handle the click event on the button and toggle the specified class on the target element.

document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('[data-toggle-target]').forEach(button => {
        button.addEventListener('click', () => {
            const targetSelector = button.getAttribute('data-toggle-target');
            const className = button.getAttribute('data-toggle-class');
            document.querySelectorAll(targetSelector).forEach(target => {
                target.classList.toggle(className);
            });
        });
    });
});

Styling with CSS

For this example, let’s add some CSS to see the effect of toggling the class.

.highlight {
    background-color: darkolivegreen;
}

Here’s a live example:

This is the content to be toggled.

Multiple Targets

You can also toggle classes on multiple target elements. Update the HTML to target multiple elements and see the changes.

<button data-toggle-target=".content" data-toggle-class="highlight">Toggle Highlight on All</button>
<div class="content">Content 1</div>
<div class="content">Content 2</div>

The HTML includes buttons with data-toggle-target and data-toggle-class attributes. The (same) JavaScript selects all elements with data-toggle-target and adds a click event listener. When a button is clicked, it toggles the specified class on the target element(s).

Here’s a live example:

Content 1
Content 2

Conclusion

Using data attributes to toggle classes in JavaScript provides a flexible and clean way to add interactivity to your webpages. This method can be extended to handle different events and more complex interactions.

Roee Yossef
Roee Yossef

I develop pixel-perfect custom WordPress themes, delivering high-performance, SEO-optimized websites. Have a project in mind? need assistance? Feel free to contact me!

0 Comments...

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!