What is event binding in jQuery?
What is event binding in jQuery?
396
09-May-2023
Updated on 15-May-2023
Aryan Kumar
15-May-2023Event binding in jQuery is the process of attaching a function to an event so that the function is called when the event occurs.
There are two ways to bind events in jQuery:
The .on() method is the preferred method for binding events in jQuery. It is more flexible and powerful than the .bind() method.
The .on() method takes three arguments:
For example, the following code binds an event handler to the click event for all elements with the class my-element:
Code snippet
The .bind() method is the older method for binding events in jQuery. It is less flexible and powerful than the .on() method.
The .bind() method takes four arguments:
For example, the following code binds an event handler to the click event for the element with the ID my-element:
Code snippet
Once an event has been bound to an element, the function that was passed to the .on() or .bind() method will be called when the event occurs.
The function that is called when an event occurs is called the event handler. The event handler can be used to perform any action that you want when the event occurs.
For example, the following code uses an event handler to change the text of an element when it is clicked:
Code snippet
When the element with the class my-element is clicked, the text of the element will be changed to "I was clicked!".
Event binding is a powerful tool that can be used to make your JavaScript code more interactive. It allows you to attach functions to events so that your code can respond to user input and other events.