JavaScript: Events and Event Listener

JavaScript: Events and Event Listener

Learn how to handle events using event listeners to make your website dynamic with the help of some easy examples

ยท

9 min read

Hello everyone! ๐Ÿ‘‹ Welcome to the world of JavaScript. Ever wondered what goes into making a website more interactive and more dynamic?๐Ÿ˜ฎ Well, when I first saw some of these websites like Google, Facebook, Netflix, and many other such websites, I was fascinated, shocked even as to how the websites responded to my every move, whether clicking on a movie recommendation or suggestion for a product, how was it all happening?๐Ÿ˜ต And that's when I learned that our every action on a website had some reaction, ๐Ÿ”ƒ and JavaScript Events and Event listeners played a part in them.

Today, we take a look at what events are and how the browser or the website reacts to some of the most common events with the help of event listeners developed by the programmers.๐Ÿ‘จโ€๐Ÿ’ป
So, let's get started!

In this blog, I will try to cover the following topics:

|-- Events
โ€ƒโ€ƒโ€ƒโ€ƒ|-- Types of events
โ€ƒโ€ƒโ€ƒโ€ƒโ€ƒ โ€ƒ | -- onchange event
โ€ƒโ€ƒโ€ƒโ€ƒโ€ƒ โ€ƒ | -- onclick event
โ€ƒโ€ƒโ€ƒโ€ƒโ€ƒ โ€ƒ | -- onload and onunload event
โ€ƒโ€ƒโ€ƒโ€ƒโ€ƒ โ€ƒ | -- Mouse events
| -- Event Listeners
โ€ƒโ€ƒโ€ƒโ€ƒ|-- Event Listener Methods
โ€ƒโ€ƒโ€ƒโ€ƒโ€ƒ โ€ƒ | -- addEventListener()
โ€ƒโ€ƒโ€ƒโ€ƒโ€ƒ โ€ƒ | -- removeEventListener()

What are Events?

Events are actions or occurrences that happen when the user tries to manipulate a webpage, the system tells us about the event, and we can respond to it accordingly.

๐Ÿ’ก For example, loading a webpage, when the user clicks a button, when we close a window (โŽ), when we press a key or resize a window, are all one or the other form of events.
๐Ÿ“ These events can be used to execute JavaScript responses, which causes the buttons to close the window, data to be validated, messages to be displayed, or any other type of response imaginable by the developer. ๐Ÿ‘จโ€๐Ÿ’ป

Common Event Types

๐Ÿ”ฐ The most common types of events in JavaScript Include:

The onchange Event

๐Ÿ“Œ The onchange event is frequently used in conjunction with the input field validation. When the value of an element is modified, the onchange event is triggered.

Example:

Enter your name: <input type="text" id="Name" onchange="upperCase()"> 
// Registering an event
<script>
function upperCase() {  // function to be triggered
  const name = document.getElementById("Name"); //getting element
  name.value = name.value.toUpperCase();     // Changing the name to uppercase 
}                                                  
</script>

๐Ÿ’ก Whenever the user changes the content of the input field, the uppercase() function will be called.

Note: The function will convert everything into uppercase on changing the content inside the input

The onclick Event

๐Ÿ“Œ The onclick event occurs whenever the user clicks on the HTML elements.

Example:

<h2 onclick="this.innerHTML='Welcome To AI Probably'">AI Probably</h2>

๐Ÿ’ก In this example, when the user clicks on the AI Probably element, the text will change to โ€œWelcome To AI Probably.โ€
๐Ÿ”ฐ A better example for your understanding would be that the window gets closed by clicking the close button(โŽ) of a website window. This event triggers an event handler or a function that will close the window as soon as the close button is clicked.

The onload and onunload Event

๐Ÿ“Œ When a user enters or leaves a page, the onload and onunload events are fired respectively.

The onload event can be used to determine the visitor's browser type and version and then load the appropriate version of the web page based on that data. Cookies can be handled using the onload and onunload events.

<body onload="load()">  // When page is loaded
    function load() {    // function gets triggered on loading
      alert("Welcome to AI Probably");
    }

๐Ÿ’ก As soon as the webpage is loaded an alert message would pop up with the message โ€œWelcome to AI Probablyโ€.
๐Ÿ“ As soon as you close the browser window, change your browser page, or reload your browser page, the onunload method is triggered.

Example:

<script>
window.onunload = (event) => {   
    alert("Thank you for visiting AI Probably");
};
// gets triggered on leaving the page,or reloading it.
</script>

๐Ÿ’ก Here when the user unloads the window, the onunload method gets triggered and an alert message pops up.

Note: Itโ€™s a good practice to use addEventListener() to register the unload event.

a)The onmouseover and onmouseout events

The onmouseover event occurs when the user mouses over an HTML element, whereas the onmouseout event is triggered when the user mouses away from the HTML element.

NOTE: Both these events are generally used together.

Example:

<div onmouseover="moveOver(this)" onmouseout="moveOut(this)" 
style="background-color:skyblue;width:160px;height:20px;padding:40px;">
Mouse Over Me</div>  // events are called on a styled box

function moveOver(obj) {    // When mouse moves over HTML element
  obj.innerHTML = "Welcome to AI Probably"    
}

function moveOut(obj) {    // when mouse moves away from HTML element
  obj.innerHTML = "Thanks for visiting"
}

๐Ÿ’ก Here, initially, before any mouse activity, we see a box with the text โ€œMouse Over Me.โ€ As soon as the user moves the mouse over the box, the onmouseover event is triggered, and the control is given to the moveOver() function, displaying a new text โ€œWelcome to AI Probably.โ€

๐Ÿ’ก When the user moves the cursor away from the box, the onmouseout event is triggered, and the control is given to moveOut() function, displaying a new text, โ€œ Thanks for visiting.โ€

Note: The โ€œMouse Over Meโ€ text is only displayed for the first time, after which the control keeps switching between the moveOver and moveOut functions.

b)The onmousedown and onmouseup events

๐Ÿ“Œ The onmousedown and the onmouseup events occur once the user clicks on the HTML element. First, on clicking the HTML elements, the onmousedown event is triggered. After that, when the user releases the mouse over the HTML element, the onmouseup event is triggered.

Example:

<div onmousedown="mouseDown(this)" onmouseup="mouseUp(this)"
style="background-color:green;width:100px;height:20px;padding:40px;">
Click Me</div> //Events are called on a styled box

function mouseDown(obj) {    // occurs when user clicks on the box
  obj.style.backgroundColor = "skyblue";
  obj.innerHTML = "Welcome to AI Probably";
}
function mouseUp(obj) {      //occurs when user releases the cursor
  obj.style.backgroundColor="yellow";
  obj.innerHTML="AI Probably";
}

๐Ÿ’ก Here, notice that when the page is loaded, you see a text โ€œClick Meโ€ with green background. As soon as the user clicks on the box, the mousedown() function is triggered, and when the user releases the mouse, the mouseup() function is triggered.

Note: Similar to onmouseover and onmouseout events, both these events onmousedown and onmouseout are generally used together.

The onfocus and onblur events

๐Ÿ“Œ The onfocus and onblur events are generally used to interact with forms. onfocus event occurs when the user clicks on the form field while the onblur event occurs when you click outside of the field.

Example:

<style>
    .incorrect { border-color: yellow; }
    #errorMsg { color: red }
  </style>
  Email Id: <input type="email" id="input"> // a form input email field
  <div id="errorMsg"></div>
  <script>
  input.onblur = function() {     // when you click outside the field
    if (!input.value.includes('@')) { 
      input.classList.add('incorrect');
      errorMsg.innerHTML = 'Please enter a valid email.'
    }
  };
  input.onfocus = function() {    // when you click inside the field
    if (this.classList.contains('incorrect')) {
      this.classList.remove('incorrect');
      errorMsg.innerHTML = "";
    }
  };
  </script>

๐Ÿ’ก Here, once the user clicks inside the email id box, the onfocus event is triggered, and the focus is given to that particular field, but as soon as the user clicks outside the field, the onblur event gets triggered, and subsequently, the border of the box changes its color to yellow and a message requesting the user to enter a valid email is displayed which disappears as soon as the user clicks back inside the field and the focus shifts to the field again.

Note: onfocus and onblur events are considered the opposite of each other.

The above mentioned events are the most common types of events that a developer uses to maintain and manipulate its web pages. ๐Ÿ‘จโ€๐Ÿ’ป

What are Event Listeners?

๐Ÿ“Œ Now letโ€™s discuss Event Listeners. Each possible event has an event handler, which is a piece of code (often a JavaScript function created by you as a programmer) that executes when the event occurs.
๐Ÿ“ We say we've registered an event handler when such a block of code is defined to run in response to an event, and these event handlers are also called event listeners.

The EventListener interface denotes an object that can respond to an event that has been dispatched by an EventTarget object. EventListener accepts both a function and an object with a handleEvent() property function

EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them. The most common event targets are Element, Document, and Window.

Example:

EventListener.handleEvent()

๐Ÿ’ก Here is a function that gets triggered whenever the specified event occurs.

EventListeners Method

๐Ÿ“Œ Now letโ€™s take a look at some EventListener methods that enable the user to either register an event handler of a specific event type on the EventTarget or remove an event listener from the EventTarget using the addEventListener() and removeEventListener() methods, respectively.

The addEventListener Method()

๐Ÿ“Œ The addEventListener() method attaches an event handler to the specified element without overwriting any existing event handlers.

Syntax:

EventTarget.addEventListener(event, function, useCapture);
  • ๐Ÿ’ก Event- Type of event i.e. , click,mouseover etc.
  • ๐Ÿ’ก Function- we want to call when the event occurs.
  • ๐Ÿ’ก useCapture- This is a parameter having a boolean value specifying to use event bubbling or event capturing.

Note: useCapture is an optional parameter.

Example:

<button id="Btn">Click Me</button> 
<script>
document.getElementById("Btn").addEventListener("click", greeting); 
// Registering an EventListener click on the button
function greeting() {  // function gets triggered on clicking the button
  alert ("Welcome to AI Probably");
}
</script>

๐Ÿ’ก Here we add an EventListener click. As soon as we click on the button, the click event occurs, and the greeting() function gets triggered, displaying an alert popup.

Example: Adding multiple event handlers to the same element

๐Ÿ“ Now we add many events to the same element without overwriting the existing events.

<button id="Btn">Click Me</button>
<script>
var welCome = document.getElementById("Btn");
welCome.addEventListener("click", greetings); // Event one
welCome.addEventListener("click", Appreciation); // Event two

function greetings() {  // trigger associated with event one
  alert ("Welcome to AI Probably");
}
function Appreciation() {  // trigger associated with event two
  alert ("Welcome to the future!");
}
</script>

๐Ÿ’ก Here first, on clicking the button, the greetings() function is triggered, displaying an alert message, after which the Appreciation() function is triggered, and a second alert message pops up.

The removeEventListener() method

๐Ÿ“Œ We use removeEventListener() method to delete event handlers previously registered using the addEventListeners() method.

Example:

<style>
    #add {    // styling around the button
      background-color: skyblue;
      border: 1px solid;
      width: 65px;
      padding: 20px;
      color: white;
      font-size: 20px;
    }
</style>
    <div id="add">
      <button onclick="removeHandler()" id="Btn">Remove</button>
        // invoking eventHandler function on clicking the button
    </div>
    <p id="remove"></p>
    <script> 
    document.getElementById("add").addEventListener("mousemove", randNumber); // adding event listener mousemove

    function randNumber() {  // function is triggered on moving mouse 
                                    around the colored button area                  
      document.getElementById("remove").innerHTML = Math.random();
    }

    function removeHandler() {
      document.getElementById("add").removeEventListener("mousemove", myFunction);  // Removes the previously added mousemove event listener
    }
    </script>

๐Ÿ’ก Here first, we add a mousemove event handler that displays a random number using the randNumber() function every time we move over the remove button or in the surrounding sky-blue-colored area.
๐Ÿ’ก To remove this event handler, the user will have to click on the button, and the removeHandler() function will get triggered.

โœ… With this, we are done with the concept of Events and EventListeners, but to truly master it and get the hang of these concepts, you should practice these concepts regularly๐Ÿ•ง with your own custom codes.
๐Ÿ’กRemember that events are like your actions and event listeners are like the consequences of your actions. ๐Ÿ”„

I hope you enjoyed this article and found it helpful!

Do check out our article on Introduction to ReactJS

For more such cool blogs and projects, check out our YouTube channel.

ย