Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove multiple event delegates using single undelegate method in jquery

Can I make the following much simpler (instead of using 'undelegate' twice)?

$("#div1").undelegate("div", "mouseenter").undelegate("div", "mouseleave");

I don't want event handlers other than mouseenter and mouseleave to get disturbed.

like image 595
user203687 Avatar asked Jul 27 '12 17:07

user203687


2 Answers

Split your events with spaces.

$("#div1").undelegate("div", "mouseenter mouseleave");

You should use on and off though.

$("#div1").off("mouseenter mouseleave", "div");

http://api.jquery.com/undelegate/

The .undelegate() method is a way of removing event handlers that have been bound using .delegate(). As of jQuery 1.7, the .on() and .off() methods are preferred for attaching and removing event handlers.

like image 176
Trevor Avatar answered Oct 05 '22 22:10

Trevor


In this specific case, you can use the shorthand .hover() for mouseenter and mouseleave.

​$("#div1").off("hover", "div");

.off() is the recommended way for removing event handlers as of jQuery 1.7.

like image 39
Alexander Avatar answered Oct 06 '22 00:10

Alexander