Using jQuery on() Method as an Alternative to JavaScript click()

In JavaScript, we can attach event listeners to an HTML element so that it 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.

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.

Get Started with jQuery

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.

Implementing jQuery on() Method in JavaScript

Let’s see some examples to demonstrate the use of jQuery on() method.

Example 1: Showing Alert Box on Click

<!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>

In the above script, we are binding a click event using jQuery’s on() to an HTML button, which when clicked shows an alert box with a message and an OK button inside the browser.

Output:

Example 2: Changing Link Color on Hover

<!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, changing the link’s DOM to a dark blue color.

Output:

Our application looks a bit ugly since we haven’t used CSS, forgot it and let’s move on to creating custom events with the jQuery on() method.

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>

In the above custom jQuery code, we have created a custom event ‘helloWorld’ which when triggered returns the message ‘Hello World!’ inside the alert.

Output:

You know we can make AJAX requests using jQuery click here to learn it.

Summary

In short, jQuery on() is used to attach event listeners and handlers to HTML elements. We can also create and trigger our custom event using this method. Attaching Events makes the website interactive and provides a better 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

jQuery API Documentation

Aditya Gupta
Aditya Gupta
Articles: 137