How to use on function jQuery

The on function in jQuery is used to attach event handlers to elements in a webpage. It allows you to specify the event that you want to listen for (e.g. a click event, a hover event, etc.), and the function that you want to execute when that event occurs.

Here is an example of how you might use the on function in your jQuery code:


$(document).ready(function() {
  $("#button").on("click", function() {
    // This function will be executed when the button is clicked
  });
});

In this example, the on function is used to attach a click event handler to the element with the ID “button”. When the button is clicked, the function inside the on function will be executed.

You can also use the on function to attach event handlers to multiple elements at once. For example:


$(document).ready(function() {
  $(".button").on("click", function() {
    // This function will be executed when any element with the class "button" is clicked
  });
});

In this example, the on function is used to attach a click event handler to all elements with the class “button”. When any of these elements are clicked, the function inside the on function will be executed.

You can also use the on function to attach event handlers to elements that are added to the page dynamically (e.g. via AJAX). To do this, you can specify a parent element as the first argument of the on function, and then specify the event and the function as usual:


$(document).ready(function() {
  $("#parent-element").on("click", ".button", function() {
    // This function will be executed when any element with the class "button" is clicked
    // within the element with the ID "parent-element", even if the element was added to the page dynamically
  });
});

This allows you to attach event handlers to elements that may not yet exist in the page when the event handler is attached.

Leave a Comment