Member-only story
jQuery to Vanilla JavaScript Transition Cheat Sheet — Events and Style Manipulation
Vanilla JavaScript in the browser now has many of the features of jQuery built-in.
Therefore, we don’t need to use jQuery to do many things.
In this article, we’ll look at the vanilla JavaScript equivalent of jQuery features.
Event Listening for Dynamically Added Elements
On many occasions, we want to listen to events on dynamically added elements.
In jQuery, we would use the on
method to listen to the event on all the select elements.
For instance, we can write:
$("div").on("click", ".search-result", (e) => {
//...
});
to listen to clicks on the elements with the search-result
class in the div with the on
method to attach the event listeners to them.
To do the same thing with vanilla JavaScript, we can use event delegation.
For instance, we can write:
document
.querySelector('div')
.addEventListener('click', (e) => {
if (e.target.className === 'search-result') {
//...
}
})
to call addEventListener
on the div.
And then in the click event handler, we use e.target.className
to get the class name of the element that we clicked on.
Then we compare that to see if we clicked on anything with the class search-result
.
Triggering and Creating Events
In jQuery, we can use the trigger
method to trigger an event.
For instance, we can write:
$(document).trigger("myEvent");
$("div").trigger("myEvent");
To do the same thing with vanilla JavaScript, we write:
document.dispatchEvent(new Event("myEvent"));
document.querySelector("div").dispatchEvent(new Event("myEvent"));
Wd call dispatchEvent
on the selected element to trigger our one event.
Styling Elements
jQuery has the css
method to let us style elements.