I wrote this function that will toggle a class of a targeted element. Applying the class js_class_toggle
to any element will trigger the function when clicking on it.
To define what the target element is and the class you want to toggle is, you have to add data-class-toggle="target_element_id.className"
to the element. You can also add this to any element on the page and it will work the same since its targeting the element by its id.
For example:
<div id="test_element" class="js_class_toggle" data-class-toggle="test_element.className">
This element will have a class toggled
</div>
JS:
$(document).on("click", ".js_class_toggle", function(e){
//Set variables
var element = $(e.currentTarget),
elementsClasses = element.attr('data-class-toggle'),
elementsClassesSplit = elementsClasses.split('.'),
targetElement = elementsClassesSplit[0],
targetClass = elementsClassesSplit[1];
//Toggle the class
$("#"+targetElement).toggleClass(targetClass);
});
Here is a working example of it: https://jsfiddle.net/fxo1a5w3/2/
What i will work on next is to be able to have multiple toggles in the same request, for example:
<div id="test_element" class="js_class_toggle" data-class-toggle="element1.className2,element2.className2">
This element will have its class toggled
</div>
But before that i want to know if there is a better way of doing what i have done so far. The goal is for it to be a function that can be used in any project.