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.
Also, adding multiple targets is also an option by separating them with a comma.

For example:

<div id="test_element" class="js_class_toggle" data-class-toggle="element_id_1.className1,element_id_2.className2">
	...
</div>

JS:

$(document).on("click", ".js_class_toggle", function(e){

	//Set variables
	var element = $(e.currentTarget),
		elementsClasses = element.data('class-toggle'),
		targets = elementsClasses.split(',');

	//Loop through all the targets
	for (var i = 0; i < targets.length; ++i) {

		//Save the current target element and the class to toggle
		var currentTarget = targets[i].split('.'),
			targetElement = currentTarget[0],
			targetClass = currentTarget[1];

		//Toggle the class
		$("#"+targetElement).toggleClass(targetClass);
	}
});

You can also add multiple targets to the event, here is a working example:

Any feedback on improvements for this would be great!

Try to avoid so complex string constructions…

<div id="test_element" class="js_class_toggle" data-class-toggle="{id_1: 'className1' , id_2: 'className2'}">
	...
</div>
$(document).on("click", ".js_class_toggle", function(e){

	//Set variables
	var element = $(e.currentTarget),
		elementsClasses = element.data('class-toggle'),
		targets = JSON.parse(elementsClasses);

	//Loop through all the targets
	for (var id in targets) {

		//Save the current target element and the class to toggle
 	         targetClass = targets[id];

		//Toggle the class
		$("#"+id).toggleClass(targetClass);
	}
});

or …

<div id="test_element" class="js_class_toggle">
	<input type="hidden" data-id="id1" data-toggle-class="class1" />
	<input type="hidden" data-id="id2" data-toggle-class="class2" />
       ….
</div>

and get this hiddens for toggle processing.

Hi there admin532,

"JavaScript ", is no longer required for this type of project. :unhappy:

Here are two CSS examples…

Replica :-

Slightly simplified :-

coothead

2 Likes

Nicely done @coothead - the best JavaScript is the code that doesn’t need to be written.

1 Like

Thanks, that does simplify the code! I didnt think about using json for it.
Though ,when i use this, it doesnt work, i get:
Uncaught SyntaxError: Unexpected token j in JSON at position 1
in the console.

I wonder how dynamic this could actually be though.
If i load an element with ajax in to the document, would this still work? would i have to have that hidden input at the top of all pages?

If i load an element with ajax in to the document, would this still work?

I answer for colleague @coothead. CSS is interpretable. So it works for any element that found in document in this moment, also loaded with AJAX.

Uncaught SyntaxError: Unexpected token j in JSON at position 1

I assume, keys in JSON include not only letters/numbers and should be quoted. Otherwise show please your JSON.

I actually copied exactly what you posted to test it, i just replaced the id_1 and ‘className’ with an actual id and class name that exists.

So i have this:
data-class-toggle="{form_loader: 'form__loading--shown'}"

EDIT:
The id i am using is actually js_form_loader thats there that unexpected j is coming from

If your actual id is id-1, in JSON that should be {‘id-1’: ‘class1’}, NOT {id-1: ‘class1’}.

And how do you create JSON? Just so or with PHP function?

I actually tried that, i just get this now: Uncaught SyntaxError: Unexpected token ' in JSON at position 1
for: data-class-toggle="{'js_form_loader': 'form__loading--shown'}"
I am just using jquery with this, no php, the function gets the data, and then as you wrote, i copied.

Ah… All should be quoted with double quotes…

data-class-toggle=“{\“js_form_loader\”: \“form__loading–shown\”}”

PHP json_encode makes this automathically.

Yes i just understood that too! i tried putting the actual string in like this:
targets = JSON.parse("{'js_form_loader': 'form__loading--shown'}"); but it didnt work, then i read that it needs to be in double quotes, then it worked.

until i changed the html element to this:
data-class-toggle='{"js_form_loader": "form__loading--shown"}'
This for some reason doesnt work, now i get this error:
VM52:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
No idea what the o is

Interesting, i guess when jquery gets the data from the element, it already parses it into json?

Because this works:



		//Set variables
		var element = $(e.currentTarget),
			elementsClasses = element.data('class-toggle');

		//Loop through all the targets
		for (var id in elementsClasses) {

			//Save the current target element and the class to toggle
 	         targetClass = elementsClasses[id];

			//Toggle the class
			$("#"+id).toggleClass(targetClass);
		}

Using it without the JSON.parse(); works

I assume, element attribute should be also double quoted. Try just…

console.log(element.data('class-toggle'));

to see, what returned.

Using it without the JSON.parse(); works

Never heard about. That’s interesting.

Yea i guess that when you store json in html, and retrieve it with JavaScript, its still json so you can just use it without parsing it. Which right now makes sense.

Thanks for the help with this, there is a little less code now which is great, it also seems more efficient.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.