Javatpoint Logo
Javatpoint Logo

jQuery off() method

The off() method in jQuery removes an event handler attached using the jQuery on() method. This method is recommended to be used as it simplifies the jQuery codebase. The off() method replaces undelegate(), unbind(), and die() methods.

Syntax

This method accepts four parameters in which one is mandatory, and others are optional. The parameter values of the off() method are defined as follows.

event: It is the mandatory parameter. This parameter specifies one or multiple events or namespaces to remove from the selected elements. If we have to specify multiple events, the event values must be separated by a space.

selector: It is an optional parameter. It should match with the one initially passed to the .on() method when attaching event handlers.

function(eventObj): It is also an optional parameter. It is the function to run when an event triggers.

map: It is the event map.

We can also use the off() method without using any arguments. If it is called without any argument, the method will remove all handlers attached to the elements. If we have to remove a particular event handler, we can provide the combinations of event names, selectors, handler function names, or namespaces.

Now, let's see some illustrations to understand the use of off() method.

Example1

In this example, there are two h3 heading elements and a button. We have to hover the elements with text Hover me, to attach the mouseover event to them. The button will remove the event attached to the h3 element.

We can check the working of the off() method by first hovering an h3 element and then clicking the button. On hovering an h3 heading, the background-color of the corresponding h3 element will get changed, and when we click on the given button, the hovering will not affect another h3 element.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery off() method

On hovering the first h3 element, the output will be -

jQuery off() method

After clicking the given button, when we hover the second h3 element, nothing will happen because the event is removed.

Example2

In this example, we are using the off() method to remove an event handler once the event has been triggered a certain number of times. Here, there is a heading h3 whose size can be increased only thrice. It is because the off() function will remove its click event once it is triggered three times. On every click, the size of the heading will increase by 4.5px.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery off() method

The heading h3 with text click me can only be clicked thrice. After clicking the text Click me three times, the output will be -

jQuery off() method





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA