Use of on() and off() function in jQuery
What is the use of on() and off() function in jQuery? Explain it with the help of an example.
An enthusiastic, adaptive, and fast-learning person with a broad and acute
interest in the discovery of new innovative drugs, I particularly enjoy
collaborating with scientists from different disciplines to develop new skills
and solve new challenges.
Aryan Kumar
14-Jun-2023The on() and off() methods in jQuery are used to attach and remove event handlers, respectively. They are both chainable methods, which means that you can call other jQuery methods on the returned object.
The on() method takes three arguments: the event type, the handler function, and an optional selector. The event type is the name of the event that you want to attach the handler to. The handler function is the function that will be called when the event is triggered. The optional selector can be used to specify a specific set of elements to which the event handler should be attached.
Here is an example of how to use the on() method to attach a click event handler to all elements with the class 'my-class':
Code snippet
The off() method takes two arguments: the event type, and an optional selector. The event type is the name of the event that you want to remove the handler from. The optional selector can be used to specify a specific set of elements from which the event handler should be removed.
Here is an example of how to use the off() method to remove a click event handler from all elements with the class 'my-class':
Code snippet
The on() and off() methods are a powerful tool that can be used to easily attach and remove event handlers from elements.
Here are some additional examples of how the on() and off() methods can be used:
Code snippet