This post will discuss the JavaScript on() method.
How is JavaScript on() Method Defined?
The “on()” method is commonly used to attach event handlers to elements, which allows developers to write functions that will be called when an event occurs, such as a “click” event, “keydown” event, a “mouseover”, and so on.
Syntax
Following syntax will be utilized for the on() method:
Here, in the above syntax:
- event: It defines the events associated with the selected element.
- function: When the event occurs, this function is called.
Example 1
First, add the jQuery library in the <head> tag, because the “on()” method is not accessible without jQuery:
In HTML document, create a <p> tag and a button with id “btn” that is utilized for accessing it:
<button id="btn">Click Here!</button>
In the <script> tag, first call the ready function, and then access the button using its assigned id and invoke the “on()” method. Pass the event parameter “click” and a function that will be called when the event occurs:
$("#btn").on("click", function () {
document.getElementById("msg").innerHTML = "Welcome To JavaScript Tutorial on Linuxhint";
});
});
The output shows that the text has been displayed on the button’s click:
Example 2
You can also just call the already defined function in the “on()” method. Here, in the given example, when the mouse is clicked on the text, the text will be changed. First, we will create a <p> tag to add a text:
Define a function named “changeText()” that will be called on the click event and change the text:
document.getElementById("msg").innerHTML = "Here You can Learn JavaScript From Scratch";
}
In the ready function, invoke the on() method on the “<p>” tag and pass the event “click” and the defined “changeText()” function:
$("p").on( "click", changeText);
});
Output
We have compiled all the necessary instructions relevant to the on() method in JavaScript.
Conclusion
The “on()” method is commonly utilized to attach an event handler to elements for adding functionality to a web page when an event occurs, such as a “click”, “keydown”, “mouseover”, and so on. This post defined the JavaScript on() method with proper examples.