With the upcoming arrival of Bootstrap 5 , more and more sites will be able to do without jQuery. For a long time I used jQuery, I found it convenient, but with today's performance requirements that directly impact SEO, every little ms is a ms gained.
Dom ready or not
A classic example is the use of the document.ready..., which is actually useless. I f you use a defer on your scripts (hint: you should!), they are already executed when the dom is ready... no need to add a layer.
$.each in vanilla js
One thing that we often find ourselves doing, is to loop on a list of elements of the dom. In modern native javascript (IE11+) nothing could be easier:
document
.querySelectorAll(selector)
.forEach(function (item) {
item.addEventListener("click", function (e) {
e.preventDefault();
console.log(item);
});
});
Classy without jQuery
Another classic example is sticky headers. Why use jQuery when a few lines are enough?
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
Or do you just want to show or hide a block? Here is another example
item.addEventListener("click", function (e) {
e.preventDefault();
var t = document.querySelector(this.getAttribute("href"));
if (window.getComputedStyle(t).display === "none") {
t.style.display = "block";
} else {
t.style.display = "none";
}
});
Note the "getComputedStyle" that lets you know whether the element is visible or hidden, whether it is via the style attribute or a css class.
Attaching behaviours
What would jQuery be without its famous plugins! Fortunately more and more javascript components take a multi framework approach and are essential written in "pure" javascript with just a wrapper around it to react, view, angular... Well, not all of them unfortunately, there are still some components that are written only for a given library.
I recently published ModularBehaviour.js which allows to attach a javascript behavior to a given node. Currently, it also works with jQuery plugins, but eventually when I will have found alternatives for all my plugins, I plan to do this in "pure" js.
Happy coding to all of you!