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
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 theonload
andonunload
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 theonmouseout
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
andmoveOut
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
andonmouseout
events, both these eventsonmousedown
andonmouseout
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
andonblur
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 anEventTarget
object.EventListener
accepts both a function and an object with ahandleEvent()
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.