How-To: Create 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.

Winery Website Development Services
Jewellery Website Development Services
Automotive Website Design Services
Drupal Website Development
Joomla Website Development
Webflow Development Services
Framer Website Development Services
WIX Development Services
Squarespace Development Services
AngularJS Website Development
ReactJS Development Services
IOS Apps Developmnet
Cross Platform App Development
Flutter App Development
Xamarin Apps Developmnet
Progressive Apps Developmnet
Prestashop Development Service
Neto (Maropost) Commerce Development Service
Shopify Plus Agency
Shopify Cro Services
Search Engine Optimization
Social Media Marketing
Paid Media Advertising
Google Ads Services
SEO Services India
Content Marketing Services
Email Marketing Services
SEO Pricing
Website Design Services India
Website Design Services USA Canada
Website Design Services British Columbia
Graphics Design Services
Logo Design
Figma To HTML5
Hire Remote Developers
Wearable App Development
Leave a Reply