jQuery bind() vs on() Methods

In this tutorial, let's discuss in detail about the bind() and on() methods of jQuery.
Submitted by Pratishtha Saxena, on August 11, 2022

1) jQuery bind() Method

It attaches a handler to an event for the elements. But here, the elements should exist previously (initially). If the element is added afterward then this method will not execute the function attached to the event handler.

Syntax:

$(selector).bind(event, function());

Code to demonstrate the use of bind() method in jQuery

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  
  <body>
    <p>This is a paragraph.</p>
    <button>Click Here</button>
  </body>
</html>

jQuery:

var x = 0;
$(document).ready(function() {
    $("button").bind("click", function() {
        $("p").css("background", "yellow");
    });
});

Output:

Example 1: bind() vs on() Methods

2) jQuery on() Method

It is a built-in method of jQuery. The on() method also attaches an event handler for the elements. It not only attaches the event handler to the present elements, but also to the elements which can be generated in near future. Unlike the bind() method, if the element is added afterward or in the future then also this method will execute the function attached to the event handler.

Syntax:

$(selector).on(event, function());

Code to demonstrate the use of on() method in jQuery

HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  
  <body>
    <p>This is a paragraph.</p>
    <button>Click Here</button>
  </body>
</html>

jQuery:

var x = 0;
$(document).ready(function() {
    $("button").on("click", function() {
        $("p").css("background", "yellow");
    });
});

Output:

Example 2: bind() vs on() Methods

Difference between bind() and on() Methods

The on() method is the preferred method for attaching event handlers to a document. For earlier versions, the bind() method is used for attaching an event handler directly to elements.






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.