Javascript DOM Events
What is an event in Javascript?
An event is an action or a state of any action performed either by the user or by the browser.
An event can be triggered by the user or by the browser. The browser triggers an event when the user interacts with the browser. The user triggers an event when the user interacts with the webpage.
Example of DOM Events are:
- User click a button
- Mouse moved
- Page loaded
- Key pressed
- Form submitted
Using Javascript you can attach and can react to certain actions. Events are generally wrapped up with some function, which executes after the event occurs.
Using these events you can make so many things because now you have control over the user's action. You can do something when the user does some action like clicking a button.
Event Terminology
There are two terminology when we come across events in web development :
- Event Listener - Event listener is an object that listens to a certain event like a click, keypress, mouse move, etc.
- Event Handler - Event handlers are generally a function that is invoked when a certain event occurs.
We can either directly attach an event to the HTML element as an attribute or we can use javascript to do this. Let's see in detail.
Adding Event Listener
Event listeners are something that keeps track of what action to be taken when a specific event occurs.
It listens to the event and fires the function. but you have to specifically mention in what event what action is to be taken.
There are 3 different ways by which you can attach an event listener to a certain element:
1. Using HTML Attribute
You can directly set an event handler to HTML element as an attribute named on<event>
and can trigger an event on that action.
For an instance if you want to attack a click
event to HTML element then use onclick
attribute to it. Example <button onclick="doSomething()">
Example
<button onclick="doSomething()" id="button">Fire Event</button>
<script>
function doSomething() {
alert("Event Fired");
}
</script>
Try It
Output:
Adding multiple event listeners :
You can see above in the code there is one event attached to the <button>
element but you can attach as many events as you want.
To attach multiple event just separate the events by a space. Example <p onevent1="doSomething()" onevent2="doSomethingElse()">
Example
<button onclick="doSomething()" onmouseover="doSomethingElse()" id="button">Fire Event</button>
<script>
function doSomething() {
alert("Event Fired");
}
function doSomethingElse() {
const button = document.getElementById("button");
button.style.background = "tomato";
button.style.padding = "5px";
}
</script>
Try It
2. Using DOM Property
Every element in the DOM has a bunch of DOM properties a list of those properties can help us to add an event listener to the element.
You can assign a event handler using DOM property on<event>
. For example, element.onclick
Example
const button = document.getElementById("button");
function message() {
alert("Event Fired");
}
button.onclick = message;
Try It
If you assign an event handler directly using HTML-attribute then the browser reads the attribute and creates a new function and assigns it to the DOM property.
Here is what it means, given below is 2 piece of code works the same:
<button id="button" onclick="alert('Event fired!')">Fire Event</button>
Example
<button id="button">Fire Event</button>
<script>
button.onclick = function () {
alert("Event Fired");
};
</script>
Both of the above codes are equivalent to each other.
While assigning function to event handler properties of DOM, just assign function name. The function should be assigned as myFxn
not myFxn()
.
3. addEventListener Method
The fundamental problem with assigning event handlers with the above method is that you can't attach 2 different event handlers for a single event.
button.onclick = function () { alert(1) }
// replaces above handler
button.onclick = function () { alert(2) }
There is another way of assigning event handlers which is free from the problem mensioned abouve, addEventListener
method.
The addEventListener
method attaches an event listener to an HTML element.
The new event attached doesn't affect previous events. You can add multiple events to the element the same way as we did use the HTML attribute.
Using addEventListener()
method you can add events to any DOM element not necessarily only HTML elements.
addEventListener syntax :
element.addEventListener(event, callback function, useCapture);
- element - It is an HTML element we are attaching event to
- event - It is the name of the event which you are interested in
- callback function - It is the function that runs after event is triggered
- useCapture - This is a boolean value that specifies whether to use event bubbling or event capturing. (This is an optional parameter and the default value is false)
Example
const element = document.getElementById("button");
element.addEventListener("click", message);
function message() {
alert("Button Clicked!")
}
Try It
While using addEventListener()
method do not use 'on' prefix in event name. like, instead of using 'onclick' just use 'click'.
You can also use an internal function as well in addEventListener()
method.
const element = document.getElementById("button");
element.addEventListener("click", function () { alert("Button Clicked!") });
Try It
Multiple event using addEventListener
The addEventListener
method can very well add multiple same or different methods to a single element. This means we can add 2 or more than 2 event listeners for the same event.
Example
const element = document.getElementById("button");
element.addEventListener("click", fxn1);
element.addEventListener("click", fxn2);
function fxn1() {
alert("Click Event Fired this function");
}
function fxn2() {
alert("Same click event fired this function too");
}
Try It
Multiple different types of events can also be attached to the same HTML element using addEventListener()
method.
Example
const element = document.getElementById("button");
element.addEventListener("click", clickFxn);
element.addEventListener("mouseover", mouseoverFxn);
element.addEventListener("mouseout", mouseoutFxn);
function clickFxn() {
alert("Click Event Fired this function");
}
function mouseoverFxn() {
element.style.background = "tomato";
element.style.padding = "8px";
}
function mouseoutFxn() {
element.style.background = "white";
element.style.padding = "2px";
}
Try It
Event Bubbling
In Event bubbling when an event is fired for the element then its first run for the element then the same event is fired for its parent element, then all the way up on another ancestor.
For example, we have three nested elements MAIN > DIV > P, and a click event is fired on 'P' then it will fire for its parent 'DIV' and then for 'MAIN'.
Example
<p>Click any element box below.</p>
<main class="border" id="main">MAIN
<div id="div">
DIV
<p id="p">P</p>
</div>
</main>
<script>
document.getElementById("p").addEventListener("click", function () { alert("P element") });
document.getElementById("div").addEventListener("click", function () { alert("DIV element also fired") });
document.getElementById("main").addEventListener("click", function () { alert("MAIN element also fired") });
</script>
Try It
Output:
P
Remove Event Listener
Event listening can also be removed from any HTML element or object.
To remove the event listener use removeEventListner()
method.
Example
<p class="tomato">This has "mouseover" event listner.</p>
<button id="button" onclick="removeEvent()">Remove Event listner</button>
<script>
var element = document.querySelector(".tomato");
element.addEventListener("mouseover", createAlert);
function createAlert(){
alert("Event Triggered!");
}
function removeEvent(){
element.removeEventListener("mouseover",createAlert);
}
</script>
Try It
Conclusion
In this tutorial, we have learned how to create, attach and remove event listeners to HTML elements. We have also learned how to use Event Bubbling
and Event Capturing
to handle events for HTML elements.