I’d like to convert jQuery to Pure JavaScript but it doesn’t work.
jQuery:
(document).ready(function()
{
$(".js-all-btn").on("click", this, function()
{
$(this).toggleClass("active");
$(".js-all-content").toggleClass("a-block");
}
);
});
To Pure:
document.addEventListener("DOMContentLoaded", function()
{
document.querySelector(".js-all-btn").on("click", this, function()
{
document.querySelector(this).toggleClass("active");
document.querySelector(".js-all-content").toggleClass("a-block");
});
});
Result:
document.querySelector(...).on is not a function
As you can see unfortunately doesn’t work. So, exactly how do we solve that?
As I couldn’t solve the problem permanently, I asked over here and my expectation is that this problem will be solved.
2
Answers
jQuery is delegating. It is not clear how to solve this without knowing if you have one or more buttons with that class
If only ONE button, do this
If more than one button you can delegate
It’s safer to also check for the current
readyState
in case the all the load events have already fired.If you have multiple buttons/contents you should use
querySelectorAll
, if you only want to get the first/single you can usequerySelector
.Have a look at the following example with a bit html and css:
Mostly ES5 (IE11 Compatible)
If you need to support an older version of IE you might have to add a polyfill for
classList.toggle