In the past, I worked quite a lot with jQuery and the thing I love about jQuery is that it provides many useful methods with simple and lightweight syntax. One of the most used jQuery methods is effects methods – which are used for creating animation effects for website.
For example:
hide() / show()
toggle()
fadeIn()
fadeOut()
…
W3schools listed all JQuery effect methods here
But now with the growth of tons of JS libraries, jQuery seems to be out of date, and in some projects, developers must replace jQuery code with pure JS.
It’s effortless to create the function act the same as hide() / show(), just edit the display style
but with more complex effects like fadeIn()/fadeOut(), we need to write more code.
Another problem with the writing effect method in vanilla JS is verbose syntax. You can see that with the jQuery method:
It is very readable and intuitive, you find the element with jQuery selector, and then call the slideDown method as the method of the element.
The code implements the same feature in vanilla JS if you define slideToggle method before:
slideToggle(element);
You query the element and then pass it to the slideToggle() function, it seems less native and less readable than the sample with jQuery.
The trick here is to use HTMLElement.prototype to add a method to the HTML element and you can use the effect function as a method of the HTML element. For simplicity, let’s define the hide() method:
this.style.display = ‘none‘
}
document.querySelector(“.myClass“).hide()
For reuse purposes, I created some vanilla JS methods for effects here. Just put it somewhere on your codebase and use it as the native method of HTML element.