jQuery Bind Events

jQuery Bind Events with Examples

In this article, I am going to discuss jQuery Bind Events with Examples. Please read our previous article, where we discussed How to detect which mouse button is clicked using jQuery. At the end of this article, you will understand all about how to bind event handlers in jQuery.

jQuery Bind Events

In the previous articles, we have learned that how to attach the event handler to any element. We have used their click(), mouseover(), mouseout() methods to bind events to any element and perform any action when the event occurs.

jQuery bind() method

The bind() method in jQuery attaches one or more event handlers for selected elements and specifies a function to run when the event occurs. The bind() method was deprecated in version 3.0. Use the on() method instead. We will see the on() method in the next article.

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

Parameters:
  1. Event: Required. Specifies one or more events to attach to the elements. Multiple event values are separated by space. Must be a valid event.
  2. Data: Optional. Specifies additional data to pass along to the function
  3. Function: Required. Specifies the function to run when the event occurs
  4. Map: Specifies an event map ({event:function, event:function, …}) containing one or more events to attach to the elements, and functions to run when the event occurs

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

Example: jQuery bind() method

At first, let us look at a simple example where we have to bind a click event to a button. In the below example, we have used the bind() method to bind the event “click” to the button

<!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</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").bind("click", function () {
          $("#Result").html("You have clicked the button");
        });
      });
    </script>
  </body>
</html>

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

jQuery Bind Events with Examples

Now click on the Click Me to see the changes button and you will see that the click event is fired as shown in the below image,

jQuery Bind Events

Example:

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 three events to the button. We are passing event objects to check event type. Then according to the condition, we are performing the handler 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</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>
      $(document).ready(function () {
        $("#btn").bind("click mouseenter mouseleave", function (event) {
          if (event.type == "click") {
            $("#Result").html(
              `Mouse pointer is at ( ${event.pageX}, ${event.pageY} )`
            );
          } else if (event.type == "mouseenter") {
            $("body").css("background-color", "#bfbfbf");
          } else {
            $("body").css("background-color", "#fff");
          }
        });
      });
    </script>
  </body>
</html>

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

jQuery Bind Method with Examples

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

jQuery Bind Method

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

Bind Method in jQuery

Example:

Now the previous example functionalities can be achieved by using ‘event map’ also. We have discussed the syntax earlier. So, modify the script section of the previous example as follows. In this example, we are using event map inside the bind() method in this syntax $(selector).bind({event:function(){}, event:function(){}, …});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  $(document).ready(function () {
    $("#btn").bind({
      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>

This is going to produce the same result as the previous example.

jQuery unbind() method

The unbind() method is used to remove event handlers from selected 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).

Note: The unbind() method was deprecated in version 3.0. Use the off() method instead. We will see the off() method in the next article.

Syntax: $(selector).unbind(event, function(){}, eventObj)

Parameters
  1. event: Optional. Specifies one or more events to remove from the elements. Multiple event values are separated by space. If this is the only parameter specified, all functions bound to the specified event will be removed.
  2. function: Optional. Specifies the name of the function to unbind from the specified event for the element
  3. eventObj: Optional. Specifies the event object to remove to use. The eventObj parameter comes from the event binding function

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

Example: jQuery unbind() method

In the below example, we will see that how to unbind some events which are already attached. In this example, we are binding the events when we are clicking on the “Bind 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 Bind Events</h1>
    <button class="btn" id="btn">Hey I'm a button !</button>
    <div class="btn-group">
      <button id="bind" class="button">Bind event</button>
      <button id="unbindClick" class="button">Unbind click event</button>
      <button id="unbindEnter" class="button">Unbind 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 () {
        $("#bind").click(function () {
          $("#btn").html("Now you can use me !!");
          $("#btn").bind({
            click: function () {
              alert("You Clicked the Button");
            },
            mouseenter: function () {
              $("body").css("background-color", "#bfbfbf");
            },
            mouseleave: function () {
              $("body").css("background-color", "#fff");
            },
          });
        });
        $("#unbindClick").click(function () {
          $("#btn").html("Oops !! Click event removed");
          $("#btn").unbind("click");
        });
        $("#unbindEnter").click(function () {
          $("#btn").html("Oh no !! mouse enter is gone");
          $("#btn").unbind("mouseenter");
        });
      });
    </script>
  </body>
</html>

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

jQuery unbind() method

  1. Now click on the Bind event and then you can use the button to see the click(), mouseenter() & mouseleave() event.
  2. Click on the ‘Unbind 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 ‘Unbind mouse enter event’. That mouse enter event will also not work.
Example:

In this example, we will see that how to remove the event object by unbind 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).unbind(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 unbind() method with Examples

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 bind() and unbind() method with Examples

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

Leave a Reply

Your email address will not be published.