This content originally appeared on DEV Community and was authored by hungle00
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
element.style.display = 'block' // or none
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:
$(".myClass").slideDown();
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:
const element = document.querySelector(".myClass");
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:
HTMLElement.prototype.hide = function() {
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.
This content originally appeared on DEV Community and was authored by hungle00
hungle00 | Sciencx (2024-07-27T02:52:20+00:00) Vanilla JS Effect Methods. Retrieved from https://www.scien.cx/2024/07/27/vanilla-js-effect-methods/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.