I appreciate the clarity of this trick that Mikael Ainalem posted over on Reddit:
It’s a one-liner that toggles the class on the <body>
so you can mock up different states and toggle between them on click.
<body onclick="this.classList.toggle("active");">
Could be on any element as well!
This can be a big thing. See “The Power of Changing Classes” as a case in point. Even if you aren’t much of a JavaScript person, classList
is perhaps the one API you should know.
The
onclick
handler is from 1996 and is something I saw way many people using and I wish less people used, because it makes implementing Content-Security-Policy harder. For learning, small tests and demos those are fine as rarely someone will implement CSP on those cases.In the other hand
classList
is from 2010 and I hope this become a big thing. Well, for me it’s already a big thing: I never useclassList
anymore (even IE 10 supports it).toggling class is so powerful but onclick attribute is not recommended. use tag and write in there or another .js file. like this:
document.querySelector("button").addEventListener(e => e.currentTarget.classList.toggle("active"));
css places in style tag or .css file and js places in script tag or .js file is major way
I think you missed this part.
“One of the tricks I use the most, when creating demos, is the body toggle active state. It quickly give me a way to test toggle states in CSS. e.g. .active .something { … }”
This isn’t in production. They’re using it to simply test different states.
I use this one from time to time:
I use it a lot.
I would like to add something else:
You can use the second parameter of the “toggle” method.
Instead of switching the class “active” we could use the second parameter as a condition, if it is true it will add the “active” class and if not it will remove the class.
https://jsfiddle.net/az2Ldpuw/ where you can check a use case where the toggle handles that only one element is active (it removes the active from the previous element that was active and adds the class to the clicked element)
I added a new version https://jsfiddle.net/az2Ldpuw/2/ where there are two use cases, a radio like situation (with the second argument) and a checkbox situation.