jQuery on() Method: Attaching Event Handlers to HTML Elements

In JavaScript, we can attach event listeners to the HTML elements so that they can become reactive and respond based on user behaviour. 

Such as we usually attach a ‘click’ event to the button to handle what happens next when a user clicks on it.

Another famous example is when we create a piano application we add a ‘click’ event to different HTML elements pretending to be piano keys and play different sounds on click.

Well, by using the jQuery on() method this will become even simpler, just a few lines of code and you can make your whole app responsive. Let’s learn about it.

jQuery on() Method

The on() method in jQuery is used to attach event listeners to the HTML elements and child elements. 

Syntax:

$(selector).on(event, function)

Here, event is the event that will be attached to the selected element and function is the event handler that specifies what happens when the attached event is triggered.

If you know Node.js async functions, it behaves the same way. Just like they have a callback that only executes when the function completes its operation, similarly, the function in the parameter here executes only when a certain action is performed. Let’s see this in action.

Implementing jQuery on() Method in JavaScript

Before using the actual method we need to initialize jQuery CDN so that our code knows what this method is. CDN stands for Content Delivery Network (CDN) to include the jQuery library in our web project.

Google CDN

<script src="https://ajax.googleapis.com/ajax/libs/jquery/{version}/jquery.min.js"></script>

jQuery Official CDN

<script src="https://code.jquery.com/jquery-{version}.min.js"></script>

If you put this line at the end or before actually calling the method the program will not be able to understand the definition of the function, so it is highly recommended to use it inside the <head> section of your HTML document. This ensures that the jQuery library is loaded before the rest of the HTML content.

Example 1:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeForGeek</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>


<button id="myButton">Click Here</button>

<script>
    $(document).ready(function() {
        $('#myButton').on('click', function() {
            alert('Button is clicked');
        });
    });
</script>

</body>
</html>

Here we are attaching a ‘click’ event to an HTML button, which when clicked shows an alert box with a message and an OK button.

Output:

Example 2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeForGeek</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        .dark-blue {
            color: darkblue;
        }
    </style>
</head>
<body>

<a href="#" id="link">Hover Here</a>

<script>
    $(document).ready(function() {
        $('#link').on('mouseover', function() {
            $(this).addClass('dark-blue'); 
        });
    });
</script>

</body>
</html>

Here we are attaching a ‘mouseover’ event to a link, when the user hovers over the link, the associated event handler is called and the link turns dark blue.

Output:

Creating Custom Events with jQuery on() Method

You know in addition to all the basic events that are available by default, you can define your own and when you want it to be triggered you can use the trigger() method with the name of the custom event passed as an argument.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeForGeek</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<button id="triggerBtn">Trigger Custom Event</button>

<script>
    $(document).ready(function() {
        $(document).on('helloWorld', function() {
            alert('Hello World!');
        });

        $('#triggerBtn').on('click', function() {
            $(document).trigger('helloWorld');
        });
    });
</script>

</body>
</html>

Here we have created a custom event ‘helloWorld’ which when triggered pops the message ‘Hello World!’ inside the alert.

Output:

Conclusion

In summary, jQuery on() is used to attach event listeners and event handlers to HTML elements. We can also create and trigger our custom event using this method. Events really make the website interactive and provide a high-quality user experience and with the help of jQuery, working with these events becomes even easier, so definitely give it a try.

Some of our best jQuery tutorials:

Reference

https://api.jquery.com

Aditya Gupta
Aditya Gupta
Articles: 116