Introduction to browser events in JavaScript

JavascriptFront End TechnologyObject Oriented Programming

An event is a signal that something has happened.

For Example, some of the built-in events in the DOM are −

  • click − A pointing device button (ANY button; soon to be primary button only) has been pressed and released on an element.

  • mouseover − A pointing device is moved onto the element that has the listener attached or onto one of its children.

  • keyup − ANY key is released

  • load − A resource and its dependent resources have finished loading.

You can create your own events using −

new Event('my-event');

You can dispatch these events on an element using dispatchEvent −

HTML 

<div id="my-div"></div>

JS 

const myDiv = document.querySelector('#my-div')
myDiv.dispatchEvent(new Event('my-event'));

You can add event listeners to define what to do on receiving events using addEventListener −

HTML 

<div id="my-div"></div>

JS 

const myDiv = document.querySelector('#my-div')
myDiv.addEventListener(
   // Event for which we want to listen
   'my-event',
   // Handler Function
   (e) => alert('Event fired!')
);
myDiv.dispatchEvent(new Event('my-event'));

Running the above code will attach an event listener to our div that will listen to my-event events. When it encounters this event it'll call the callback function.

Since we're dispatching this event, it'll be fired immediately and we'll see the alert box.

raja
Published on 02-Dec-2019 10:47:59
Advertisements