Binding Event Handlers using jQuery on Method

Binding Event Handlers using jQuery on Method

In this article, I am going to discuss Binding Event Handlers using the jQuery ON Method with Examples. In the previous article, you have learned that how to attach an event handler to any element by the bind() method. In this article, we will see how to do this using the On() method.

jQuery On() method

The on() method in jQuery attaches one or more event handlers for selected elements or children elements and specifies a function to run when the event occurs. As of jQuery version 1.7, the on() method is the new replacement for the bind() method. This method brings a lot of consistency to the application, and jQuery recommends using the on() method to attach event handlers.

Syntax: $(selector).on(event, childSelector, data, function, map)

Parameters:
  1. event: Required. Specifies one or more event(s) or namespaces to attach to the selected elements. Multiple event values are separated by space. Must be a valid event.
  2. childSelector: Optional. Specifies that the event handler should only be attached to the specified child elements.
  3. data: Optional. Specifies additional data to pass along to the function.
  4. function: Required. Specifies the function to run when the event occurs.
  5. map: Specifies an event map ({event:function, event:function, …}) containing one or more events to attach to the selected elements, and functions to run when the events occur.

(Reference: https://www.w3schools.com/jquery/event_on.asp)

Example: Bind Click Event using jQuery ON Method

At first, let us look at a simple example where we have to bind a click event to a button using the on() method. In the below example, we have used the on() method to bind the event “click” to the button. The usage of the bind() and on() methods are very similar. What you have to do, just put on() instead of bind().

<!DOCTYPE html>
<html lang="en">
  <head>
        <title>jQuery Bind Events Using on() Method</title>
  </head>
  <body>
    <h1>jQuery Bind Events Using ON Method</h1>
    <input id="btn" type="button" value="Click Me to see the changes" />
    <p id="Result"></p>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#btn").on("click", function () {
          $("#Result").html("You have clicked the button");
        });
      });
    </script>
  </body>
</html>

Now, run the above code and you will get the following output.

Bind Click Event using jQuery ON Method

Now click on the Click Me to see the changes button and you will see the following output in the browser.

Bind Click Event using jQuery ON Method with Examples

Example: Bind Multiple Events using jQuery ON Method

Now let us see how to bind multiple events to an element. When you are binding multiple events, those events should gap by a “space”. In the below example, we have bound two events to the card. When you will hover on the card the details will be shown. When you leave your pointer out the details will be hidden.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        background-color: #ddd;
        font-family: Arial, Helvetica, sans-serif;
      }
      .card {
        box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
        transition: 0.3s;
        width: 30%;
        margin: auto;
      }
      img {
        width: 100%;
        height: 300px;
      }

      .card:hover {
        box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
        cursor: pointer;
      }

      .container {
        padding: 10px 16px;
        display: none;
      }
      button {
        background-color: #1c4450;
        border: none;
        color: white;
        padding: 10px 25px;
        margin: 10px 0;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
      }
    </style>
  </head>
  <body>
    <div class="card">
      <img src="C:\Users\HP\OneDrive\Pictures\img_avatar.jpg" alt="Avatar" />
      <div class="container">
        <h4><b>John Doe</b></h4>
        <p>Web Developer & Designer</p>
        <button>Know More</button>
      </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(".card").on("mouseenter mouseleave", function () {
        $(".container").toggle(500);
      });
    </script>
  </body>
</html>

Now run the above code and hover the mouse pointer over the image and you will see the details as shown in the below image.

Bind Multiple Events using jQuery ON Method

Now leave the mouse pointer from the image and the details will be hidden as shown in the below image.

Bind Multiple Events using jQuery ON Method with Examples

Example: jQuery ON Method using Map

Now let’s see how to use event map using on() method. In the below example, we are using event map inside the on() method in this syntax: $(selector).on({event:function(){}, event:function(){}, …}) 

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      body {
        font-family: Arial, Helvetica, sans-serif;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
      }
      p {
        margin: 20px;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
      }
      #btn {
        background-color: #1c4450;
        border: none;
        outline: none;
        color: white;
        padding: 20px 35px;
        margin: 20px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
        text-transform: uppercase;
      }
      #btn:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
          0 17px 50px 0 rgba(0, 0, 0, 0.19);
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
    </style>
  </head>
  <body>
    <h1>jQuery Bind Events using on()</h1>
    <input id="btn" type="button" value="Use Me to see the changes" />
    <p id="Result"></p>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $("#btn").on({
          click: function () {
            $("#Result").html(
              `Mouse pointer is at ( ${event.pageX}, ${event.pageY} )`
            );
          },
          mouseenter: function () {
            $("body").css("background-color", "#bfbfbf");
          },
          mouseleave: function () {
            $("body").css("background-color", "#fff");
          },
        });
      });
    </script>
  </body>
</html>

When you will hover on the button, you will get the following output.

Binding Event Handlers using jQuery on Method

When you will put your pointer out of the button, you will get the following output.

Binding Event Handlers using jQuery on Method with Examples

When you click on the button, you will get the following output.

jQuery ON Method using Map

jQuery off() method

The off() method is used to remove event handlers from selected elements or children of elements. This method can remove selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object. This is used to unbind an event from within itself (like removing an event handler after the event has been triggered a certain number of times).

As of jQuery version 1.7, the off() method is the new replacement for the unbind() method. This method brings a lot of consistency to the application, and jQuery recommends using the off() method to remove event handlers.

Syntax: $(selector).off(event, selector, function(eventObj), map)

Parameter
  1. event: Required. Specifies one or more events or namespaces to remove from the selected element(s). Multiple event values are separated by a space. Must be a valid event
  2. selector: Optional. A selector which should match the one originally passed to the on() method when attaching event handlers
  3. function(eventObj): Optional. Specifies the function to run when the event occurs
  4. map: Specifies an event map ({event:function, event:function, …}) containing one or more event to attach to the elements, and functions to run when the events occur

(Reference: https://www.w3schools.com/jquery/event_off.asp)

Example: jQuery off() method

In the below example, we will see that how to unbind some events using the off method which is already attached. In the below example, we are binding the events when we are clicking on the “On event” button. Then we are unbinding the events by clicking the corresponding buttons

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        font-family: Arial, Helvetica, sans-serif;
        display: flex;
        justify-content: center;
        flex-direction: column;
        align-items: center;
      }
      p {
        margin: 20px;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
      }
      .btn {
        background-color: #1c4450;
        border: none;
        outline: none;
        color: white;
        padding: 20px 35px;
        margin: 20px;
        margin-bottom: 40px;
        text-align: center;
        text-decoration: none;
        display: inline-block;
        font-size: 16px;
        border-radius: 10px;
        cursor: pointer;
        transition-duration: 0.4s;
        text-transform: uppercase;
      }
      .btn:hover {
        box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24),
          0 17px 50px 0 rgba(0, 0, 0, 0.19);
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
      .btn-group .button {
        background-color: #3c7072;
        border: 1px solid rgb(36, 109, 103);
        outline: none;
        color: white;
        padding: 15px 32px;
        text-align: center;
        text-decoration: none;
        font-size: 16px;
        cursor: pointer;
        float: left;
      }

      .btn-group .button:not(:last-child) {
        border-right: none;
      }

      .btn-group .button:hover {
        background-color: #194849;
      }
    </style>
  </head>
  <body>
    <h1>jQuery on() & off() method</h1>
    <button class="btn" id="btn">Hey I'm a button !</button>
    <div class="btn-group">
      <button id="on" class="button">on event</button>
      <button id="offClick" class="button">off click event</button>
      <button id="offEnter" class="button">off mouse enter event</button>
    </div>
    <p id="Result"></p>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        $("#on").click(function () {
          $("#btn").html("Now you can use me !!");
          $("#btn").on({
            click: function () {
              alert("You Clicked the Button");
            },
            mouseenter: function () {
              $("body").css("background-color", "#bfbfbf");
            },
            mouseleave: function () {
              $("body").css("background-color", "#fff");
            },
          });
        });
        $("#offClick").click(function () {
          $("#btn").html("Oops !! Click event removed");
          $("#btn").off("click");
        });
        $("#offEnter").click(function () {
          $("#btn").html("Oh no !! mouse enter is gone");
          $("#btn").off("mouseenter");
        });
      });
    </script>
  </body>
</html>

When you run the above code, you will get the following output.

jQuery off() method

  1. Click on the event. Now you can use the button to see the click(), mouseenter() & mouseleave() methods
  2. Click on the ‘off click event’ button. Now the click event is removed. No functionality will occur if you click the button. But mouse enter event will work
  3. Now click on the ‘off mouse enter event’. That mouse enter event will also not work
Example: jQuery On and Off Method

In the below example, we will see that how to remove the event object by the off() method. In this example, you can enlarge this image 2 times. After that, we are removing the event object and then if you further double click on the image, a message will be shown.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <style>
      body {
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        font-family: Arial, Helvetica, sans-serif;
      }
      h1 {
        font-size: 40px;
        margin-bottom: 30px;
        padding: 30px;
        text-align: center;
        text-transform: capitalize;
        font-style: italic;
      }
      img {
        width: 300px;
        height: 300px;
        transition: 0.3s;
      }
      p {
        margin: 20px;
        font-weight: bold;
        font-size: 30px;
        text-align: center;
        font-style: oblique;
      }
    </style>
  </head>
  <body>
    <h1>Double Click to Zoom the image</h1>
    <img src="C:\Users\HP\OneDrive\Pictures\MyImage.JPG" alt="image" />
    <p id="result"></p>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
        var x = 0;
        $("img").dblclick(function (event) {
          $(this).css({ width: "+=100px", height: "+=100px" });
          x++;
          if (x >= 2) {
            $(this).off(event);
            $("img").dblclick(function () {
              $("#result").html("you cannot zoom this image further");
            });
          }
        });
      });
    </script>
  </body>
</html>

When you run the above code, you will get the following output.

jQuery On and Off Method

Now, double click two times on the image and it will be enlarging. But when you double click the third time on the image, it will give you the following message.

jQuery On and Off Method with Examples

In the next article, I am going to discuss Passing Data to the Event Handler in jQuery with Examples. Here, in this article, I try to explain Binding Event Handlers using jQuery on Method with Examples and I hope you enjoy this How to Bind Event Handlers in jQuery using ON Method article.

Leave a Reply

Your email address will not be published.