Home > Web Front-end > JS Tutorial > body text

Vanilla JS Effect Methods

PHPz
Release: 2024-07-27 15:02:23
Original
785 people have browsed it

Vanilla JS Effect Methods

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
Copy after login

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();
Copy after login

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);
Copy after login

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()
Copy after login

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.

The above is the detailed content of Vanilla JS Effect Methods. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!