jQuery dynamic toggle class function 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:

&lt;div id="test_element" class="js_class_toggle" data-class-toggle="test_element.className"&gt;
    This element will have a class toggled
&lt;/div&gt;


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:

&lt;div id="test_element" class="js_class_toggle" data-class-toggle="element1.className2,element2.className2"&gt;
    This element will have its class toggled
&lt;/div&gt;


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.
You can access the data element via dataset property and camelCase data name

const data = element.dataset.classToggle;


You can add a click event to the document as follows that will only do something if the target is class js_class_toggle

const togClass = `.js_class_toggle`;

addEventListener("click", e =&gt; {
    if (e.target.classList.contains(togClass)) {
        /* ...do stuff... */
    }
}


Or you can add a click to each element containing the class.

document.querySelectorAll(togClass).forEach(el =&gt; el.addEventListener("click", toggleClick));


By the looks you are toggling the class on the element that is clicked so there is no need to add the reference

&lt;div class="js_class_toggle toggle-me" data-class-toggle="toggle-me"&gt;
    This element will have a class toggled
&lt;/div&gt;


making the function to toggle very simple

function toggleClick(e) {
     e.target.classList.toggle(e.target.dataset.classToggle);
}


To include the reference id you can make the data JSON like

&lt;div id = "foo" class="js_class_toggle toggle-me" 
    data-class-toggle='{"query": "#foo", "toggleClass": "toggle-me"}'&gt;
    This element will have a class toggled
&lt;/div&gt;


Then the function becomes

function toggleClick(e) {
     const data = JSON.parse(e.target.dataset.classToggle);
     const el = document.querySelector(data.query);
     if (el) { el.classList.toggle(data.toggleClass) }
}