Main Menu
Your email has been received and will be responded to as soon as possible.
We are available 24/7 to take your call.

Our Blog

21 February 2022
ioadmin

How-To: Create Easy Element Toggles with Data Attributes and jQuery.

Easy Element Toggles with Data Attributes and jQuery.

While working on my latest WordPress plugin, I found myself using jQuery toggleClass on multiple elements and writing JS code for each was not at all a better solution. To fix this issue and keep the code clean and short I used the following code.

$(document).on('click', '[data-toggle="class"]', function () {
    var $target = $($(this).data('target'));
    var classes = $(this).data('classes');
    $target.toggleClass(classes);
    return false;
});

Make sure you have jQuery script on your page and add this code to your Javascript file and then you can use it in your HTML code as below:

<a href="#" data-toggle="class" data-target="#element" data-classes="is-active">Click here</a> to toggle.
<div id="element">...content goes here...</div>

The anchor tag with data-toggle will look for an element with ID or element and toggle is-active class for that element. You can apply this logic to any UI element such as Modal with an overlay background and use the data-toggle attributes on the modal background as well to hide the modal.

Feel free to implement and extend this code on your projects.

contact us

Our services

Leave a Reply

Your email address will not be published. Required fields are marked *

Request A Quote Now

Enquiry Now

When We Work Together

We can create something incredible

arrow
HQ INDIA
HQ INDIA
C-31, Milap Nagar,
Uttam Nagar, New Delhi,
Delhi 110059
USA
USA
6715 Backlick Rd Suite 202
Springfield,
VA 22150, USA
AUSTRALIA
AUSTRALIA
2/51, Lane Cres,
Reservoir, VIC
3037, Australia
CANADA
CANADA
61 Payzant Bog Road, Falmouth, NS, B0P 1P0, CANADA
UK
UK
3rd Floor, 131 City Road, London, EC1V 2NX, United Kingdom
UAE
UAE
Boutik Mall, Al Reem Island - Abu Dhabi, UAE
X

Let Us Call You Back

  • India+91
  • United States+1
  • United Arab Emirates+971

Your phone number is kept confidential
and not shared with others.