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 custom WordPress themes by design. I love typography, colors & everything between, and aim to provide high performance, seo optimized websites with a clean & semantic code.

0 Comments...

Leave a Comment

Add code using the buttons below. For example, to add PHP click the PHP button & add the code inside the shortcode. Typo? Please let us know...

Recently Updated