jQuery unbind()
×


jQuery unbind()

1680

  • This function is used in jQuery to remove one or more event handlers to one or more HTML DOM elements.
  • It stops a function to run when the event occurs.
  • This function can also unbind event handlers using an event object

Related Topics:

jQuery dblclick
jQuery bind

jQuery unbind

Syntax:

$(selector).unbind(event,function,eventObj);

Parameter description:

  • event: This parameter represents one or more events to remove from the elements. Multiple event values can be added by separating each of them by commas. It is an optional parameter.
  • function: This represents a function that you want to unbind from the specified event for the element. It is also an optional parameter.
  • eventObj: This represents the event object to remove to use. It is also an optional parameter.
Note:

The unbind() method will remove ALL event handlers from the specified element if no parameters are specified.

Example 1

In this example, we will learn how to use the unbind() method to unbind a specific function from a specified event for an element.

<html>
<head>
<title>jQuery Example</title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
function myFunction() {
alert($("p").html());
}

$(document).ready(function(){
$("p").click(myFunction);
$("button").click(function(){
$("p").unbind("click");
alert("click event removed.");
});
});
</script>
</head>
<body>

<h2>jQuery Unbind event Example</h2>
<p>Hello friends! welcome to CodingTag.</p>
<button>Remove click event of above paragraph.</button>
</body>
</html>

Output:

When you click on the paragraph, an alert box will open which contains the text of the paragraph.

To remove this event click on the button,

Now, if you click again on the paragraph no alert box will open.


Example 2

In this example, we will learn how to Specifies an event object to remove.

With the help of this example, we change the color of paragraph text exactly 4 times.

<html>
<head>
<title>jQuery Example</title>
<script type = "text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var color= ["red", "green", "blue","yellow"];
var i = 0;
$("p").click(function(e){
$("p").css("color",color[i]);
i++;
if (i > 3) {
$(this).unbind(e);
}
});
});
</script>
</head>
<body>

<h2>jQuery Unbind event Example</h2>
<p>Click this p element to change the colour. The colour can only be changed 4 times.</p>
</body>
</html>

Output:

In the first click,

In the second click,

In the third click,

In the fourth click,



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments