Table of Contents
In this tutorial, we will look into events in JavaScript. As you already know, Javascript is a scripting language that runs inside web browsers. It allows developers to add interactive features to websites without having to write code. One of its main uses is to create dynamic user interfaces. For example, you may want to show a message or play a sound when someone clicks on a button. This can be easily achieved through the use of events in JavaScript. We will understand more about events with the help of some of the detailed examples in below section. Check more about events on Mozilla official website.
What are Events in JavaScript [Explained with examples]
Also Read: How does JavaScript double question mark (??) operator works
Events are actions or things that happen at certain times. They are triggered by something else happening. For example, clicking on a button triggers a function to run. In programming, events are often used to trigger functions.
Events are used to trigger functions. The event listener is attached to an element (e.g., a button) and listens for changes in the state of the element. When the state of the element changes, the event listener executes its associated code. This allows us to write our code once and reuse it across multiple elements.
Event Listener
Event listeners are used to detect events like clicks, key presses, mouse movements, etc. They allow developers to respond to these events in order to perform some action. For instance, when a user clicks on a button, we may want to display a message saying “You clicked on the button!”. We can achieve this by adding event listeners to the buttons.
How to Create an Event Listener
You can attach an event listener to a DOM element like a button or input field. To do this, first find out what type of object the DOM element is. Let's say you're trying to make an event listener for a button. First, you'd need to find out what kind of object the button is. Next, you'd need to locate the ID of the button. Once you've found the ID, you can attach an event listener using the following code below:
element.addEventListener(type,eventListener);
Event listeners are used to listen for events in JavaScript. They allow developers to react to certain actions happening within a web page. Here we'll learn how to write an event listener in JavaScript. We'll also look at some common uses for event listeners.
NOTE:
Step 1: Create a Button Element
First, let’s create a button element.
<button> please click me</button>
Step 2: Add an ID Attribute
Next, we need to give the button an id attribute.
<button id="demo">please click me</button>
Step 3: Set Up the OnClick Functionality
Now, we need to set up the functionality of the button. First, we need to define the function that will run whenever the button is pressed. Let’s call it myFunction().
<button id="demo" onclick="myFunction()"> please click on me.</button>
Step 4: Define the Click Event Handler
We also need to define the click event handler. When a user clicks on the button, we want to execute the function defined above. So, we need to attach the click event to the button.
Add the following line inside the body tag:-
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "you clicked on me!";
}
</script>
Step 5: Run the Code
Finally, we need to run the code.
Output
You should see the text “You clicked on me!” displayed inside the button.
Common Uses of Event Listeners
Event listeners are useful for things like form validation, changing colors, and animating elements. Here are some examples:-
a) Form Validation: You can use event listeners to validate forms. For instance, let's say you wanted to make sure that only numbers were entered into a text box. You could set up an event listener that detects changes in the value of the textbox and prevents the submit button from being clicked until all fields are filled out correctly.
Validate forms with JavaScript is pretty straightforward. All you need to do is attach an event listener to the form element and call the validation function when the user submits the form. But sometimes we need to validate multiple fields at once. For instance, let’s say we have a form with four input boxes that needs to be validated before submitting. We could write a separate validation function for each field but that gets tedious fast.
So instead, we can use an event listener to trigger all the validations at once. We can attach an event listeners to the elements that you want to validate. For example, here’s a simple HTML form with some text inputs:-
<form onSubmit="return validateEmail();">
Please enter your email.<br>
<input type="text" id="emailField">
<input type="submit" value="Submit">
</form>
Now, let’s attach an event listener to the email fields so that when the user clicks submit, the validation functions run. To do that, paste the following javascript code provided:-
const validateEmail = () => {
const emailField = document.getElementById("emailField");
const regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\. \-]+\.[a-zA-z0-9]{2,4}$/;
if (!(regex.test(emailField.value))) {
alert("Please correct email address");
return false;
}
}
Output
b) Animations: You can use event handlers to animate objects on a webpage. For example, you could change the color of an image whenever a mouse hovers over it and when you animate something, you usually want to listen to some events. For instance, when you click on a button, you may want to change its color. Or maybe you want to play a sound from a music file when the user clicks on a link.
In this tutorial, we will see how to animate things like buttons, divs, textboxes, etc. using JavaScript events. Let's begin!
Step 1: Create a paragraph element
<p><a id="anim" href="#">Click me to Animate!</a></p>
Step 2: Add Event Listeners
// button click event
anim.addEventListener("click", ToggleAnimation, false);
// animation listener events
PrefixedEvent(anim, "AnimationStart", AnimationListener);
PrefixedEvent(anim, "AnimationIteration", AnimationListener);
PrefixedEvent(anim, "AnimationEnd", AnimationListener);
Step 3: Add CSS Styles
body
{
font-family: arial, helvetica, freesans, sans-serif;
font-size: 100%;
color: #333;
background-color: #ddd;
}
h1
{
font-size: 1.5em;
font-weight: normal;
margin: 0;
}
pre
{
height: 20em;
font-family: monospace;
font-size: 1em;
padding: 2px 5px;
color: rebeccapurple;
background-color:wheat;
border: 1px solid #030;
border-radius: 4px;
overflow: auto;
}
#anim
{
display: block;
width: 14em;
font-size: 1.3em;
font-weight: bold;
text-align: center;
text-decoration: none;
padding: 0.5em 3em;
margin: 2em auto;
color: #fff;
background-color: #060;
border: 2px solid #393;
border-radius: 5px;
outline: 0 none;
}
#anim.enable
{
color: #333;
background-color: #0c0;
box-shadow: 0 0 5px #0f0;
-webkit-animation: flash 2s ease 4;
-moz-animation: flash 2s ease 4;
-ms-animation: flash 2s ease 4;
-o-animation: flash 2s ease 4;
animation: flash 2s ease 4;
}
/* animation */
@-webkit-keyframes flash {
60% { opacity: 0; }
}
@-moz-keyframes flash {
60% { opacity: 0; }
}
@-ms-keyframes flash {
60% { opacity: 10; }
}
@-o-keyframes flash {
40% { opacity: 0; }
}
@keyframes flash {
70% { opacity: 0; }
}
Step 4: Add Animation
/ start/stop animation
function ToggleAnimation(e) {
var on = (anim.className != "");
LogEvent("Animation is " +(on ? "disabled.\n" : "enabled."));
anim.textContent = "Click to "+(on ? "start" : "stop")+" animation";
anim.className = (on ? "" : "enable");
if (e) e.preventDefault();
};
Here is the complete code to run:-
<html><head> <meta charset="UTF-8"> <title>animation</title> <style> body { font-family: arial, helvetica, freesans, sans-serif; font-size: 100%; color: #333; background-color: #ddd; } h1 { font-size: 1.5em; font-weight: normal; margin: 0; } pre { height: 20em; font-family: monospace; font-size: 1em; padding: 2px 5px; color: rebeccapurple; background-color:wheat; border: 1px solid #030; border-radius: 4px; overflow: auto; } #anim { display: block; width: 14em; font-size: 1.3em; font-weight: bold; text-align: center; text-decoration: none; padding: 0.5em 3em; margin: 2em auto; color: #fff; background-color: #060; border: 2px solid #393; border-radius: 5px; outline: 0 none; } #anim.enable { color: #333; background-color: #0c0; box-shadow: 0 0 5px #0f0; -webkit-animation: flash 1s ease 3; -moz-animation: flash 1s ease 3; -ms-animation: flash 1s ease 3; -o-animation: flash 1s ease 3; animation: flash 1s ease 3; } /* animation */ @-webkit-keyframes flash { 50% { opacity: 0; } } @-moz-keyframes flash { 50% { opacity: 0; } } @-ms-keyframes flash { 50% { opacity: 0; } } @-o-keyframes flash { 50% { opacity: 0; } } @keyframes flash { 50% { opacity: 0; } } </style> </head> <body> <h1>Animation Events in JavaScript</h1> <p>When you click the butto a class of "enable" is applied to the element which starts an animation. Animation start, iteration and end events are captured and logged. When animation end is encountered, the "enable" class is removed.</p> <p><a id="anim" href="#">Click me to Animate!</a></p> <pre id="log">log information</pre> <script> var anim = document.getElementById("anim"), log = document.getElementById("log"), pfx = ["webkit", "moz", "MS", "o", ""]; // button click event anim.addEventListener("click", ToggleAnimation, false); // animation listener events PrefixedEvent(anim, "AnimationStart", AnimationListener); PrefixedEvent(anim, "AnimationIteration", AnimationListener); PrefixedEvent(anim, "AnimationEnd", AnimationListener); // apply prefixed event handlers function PrefixedEvent(element, type, callback) { for (var p = 0; p < pfx.length; p++) { if (!pfx[p]) type = type.toLowerCase(); element.addEventListener(pfx[p]+type, callback, false); } } // handle animation events function AnimationListener(e) { LogEvent("Animation '"+e.animationName+"' type '"+e.type+"' at "+e.elapsedTime.toFixed(2)+" seconds"); if (e.type.toLowerCase().indexOf("animationend") >= 0) { LogEvent("Stopping animation..."); ToggleAnimation(); } } // start/stop animation function ToggleAnimation(e) { var on = (anim.className != ""); LogEvent("Animation is " +(on ? "disabled.\n" : "enabled.")); anim.textContent = "Click to "+(on ? "start" : "stop")+" animation"; anim.className = (on ? "" : "enable"); if (e) e.preventDefault(); }; // log event in the console function LogEvent(msg) { log.textContent += msg + "\n"; var ot = log.scrollHeight - log.clientHeight; if (ot > 0) log.scrollTop = ot; } </script> </body></html>
Output
Conclusion
In this tutorial, we have seen what are events, what are event listener and how it works with the help of detailed examples. Just to wrap it up, an event listener is used to detect events such as clicks, key presses, and mouse moves. It allows developers to react to these events in order perform some action.