Event Firing in JavaScript


Events in JavaScript are the actions performed by the browser or the user. Some of the examples of events are −

  • On webpage load

  • On keypress

  • On hover

  • On click, etc.

When javascript code is embedded in HTML runs, js reacts to these events and allows the code to run. Whenever these JavaScript codes are executed we call it firing an event.

Example

Let’s see an easy example to understand the whole concept of event firing, from beginning to end.

<html>
<body>
   <button id="dmrc">Click me!! I change number.</button>
   <p id="num"></p>
   <script>
      const btn = document.getElementById("dmrc");
      btn.addEventListener('click', () => {
         document.getElementById("num").innerHTML=Math.floor(Math.random()*100);
      });
   </script>
</body>
</html>

In the example above, the HTML part is a button and paragraph (<p>). Here, firstly we are storing the reference of the button in the variable called “btn” using document.getElementById() function.

Then, we have an event listener with the “click” keyword which will capture for any click event happening to the button. Whenever the button is clicked the event listener gets activated and returns a random number from 1 to 99 and gets displayed in the paragraph <p> with the id=”num”.

Firing events using addEventListener

The method we are going to use is addEventListener(). Basically, addEventListener() is a function that takes two parameters. Firstly, the event name and secondly, handler function.

Syntax

addEventListener(EventName,EventHandlerFunction());

Example

We specify two parameters inside the addEventListener() function: the name of the event for which we want to register this handler and the code containing the handler function we want to run in response to it.

<html>
<body>
   <button id="dmrc">Click me!! I change number.</button>
   <p id="num"></p>
   <script>
      const btn = document.getElementById("dmrc");
      function changeNum(){
         document.getElementById("num").innerHTML=Math.floor(Math.random()*100);
      }
      btn.addEventListener('click', changeNum);
   </script>
</body>
</html>

The difference between this code and the code above is, we are defining the handler function using a separate name. There are endless possibilities of using these functions in different ways, it is recommended that you must play around these functions and methods.

Various ways of firing events

Let’s experiment with our button by applying various kinds of firing events and handler function.

It is recommended to make a .HTML file and try changing the click keyword with various other actions listed below and play around accordingly.

Using dblclick to fire event

In this, the event will fire on double click of the mouse instead of a single click shown in previous examples.

Syntax

addEventListener('dblclick', ()=>{ } );

Example

<html>
<body>
   <button id="dmrc">Double Click me!! I change number.</button>
   <p id="num"></p>
   <script>
      const btn = document.getElementById("dmrc");
      function changeNum(){
         document.getElementById("num").innerHTML=Math.floor(Math.random()*100);
      }
      btn.addEventListener('dblclick', changeNum);
   </script>
</body>
</html>

Using focus & blur to fire event

When the button is focused and unfocused, the number changes; try clicking the tab to focus on the button and hitting the tab again to focus away from the button. When focused, they are frequently used to display information about filling in form fields or to display an error message if invalid value is filled.

Syntax

btn.addEventListener('focus', changeNum);
btn.addEventListener('blur', changeNum);

Example

<html>
<body>
   <button id="dmrc">Click me!! I change number.</button>
   <p id="num"></p>
   <script>
      const btn = document.getElementById("dmrc");
      function changeNum(){
         document.getElementById("num").innerHTML=Math.floor(Math.random()*100);
      }
      btn.addEventListener('focus', changeNum);
      btn.addEventListener('blur', changeNum);
   </script>
</body>
</html>

Here, we are just changing the keyword from click to focus or dblclick. Hence, it is recommended to find such action keywords and play around with the example code above.

Few of such keywords are mouseover, mouseout, scroll, etc.

Other ways of firing events

Although we have a powerful and scalable method for handling the events i.e addEventListener(), sometimes we may require the use of other ways of handling the events. Event handler properties and inline event handlers are the other two ways by which we can handle the events.

Event handler properties

Objects such as “Buttons” have properties like on+eventName. For example, onclick. This is called event handler properties. The drawback of using this method is, we can not use multiple action events with a single object.

Example

<html>
<body>
   <button id="dmrc">Click me!! I change number.</button>
   <p id="num"></p>
   <script>
      const btn = document.getElementById("dmrc");
      btn.onclick = () =>{
         document.getElementById("num").innerHTML=Math.floor(Math.random()*100);
      }
   </script>
</body>
</html>

Inline event firing

It is the oldest and not recommended method for handling the events. When the event occurs, the property value is literally the JavaScript code you wish to perform. Here, script tag is not used which will make the code messy and tough to handle big project if done by this method.

Example

<!DOCTYPE html>
<html>
<body>
   <button onclick="document.getElementById('tut').innerHTML=Date()">click me to know time.</button>
   <p id="tut"></p>
</body>
</html>

Conclusion

In this tutorial, we learned about the various ways of firing the events. We started with the method called addEventListeners and finally concluded with many ways for event firing with various running code examples.

Updated on: 19-Jan-2023

779 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements