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.
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.
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.
Related
What is difference between window.resize() and window.on('resize' , function())
in jquery?
From jQuery page .resize():
This method is a shortcut for .on('resize', handler).
and .on() is:
The .on() method attaches event handlers to the currently selected
set of elements in the jQuery object. As of jQuery 1.7, the .on()
method provides all functionality required for attaching event
handlers. For help in converting from older jQuery event methods, see
.bind(), .delegate(), and .live().
So based on jQuery api description, I think there is no difference it's just a shortcut similar to $.click() and others
There was no difference between $("#element").resize() and $("#element").on('resize' , function()). The former was a shorthand for the latter. However, as of jQuery 3 the event shorthand is deprecated. This also applies to the following event shorthands: blur, click, focus, focusin, focusout, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu.
I have one anchor element in my page
Click
I know in jQuery we have so many ways of binding events to element like (bind, live, delegate, on).
FYI:
http://blog.tivix.com/2012/06/29/jquery-event-binding-methods/
Currently using jquery1.8.3.min.js. I want to know which one is standard and efficient event registration model in jQuery?
Currently I am doing it like this:
$("#page").click(function(){
................................
});
Can I change to bind like below code:
$("#page").bind("click",clickFunc);
function clickFunc()
{
..........
}
Which one is best practice to register the event in jQuery 1.8 ?
The best way is the way one can understand what's written and the one that works.
The smart way is to use what's suggested to use, in this case the .on() method:
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). To remove events bound with .on(), see .off(). To attach an event that runs only once and then removes itself, see .one()
The how-to way depends if you need to delegate your event/s to dynamically generated elements or not.
$('.child').on( 'click', function() { /* ... */ });
$('#parent').on( 'click', ".dyn-gen-child", function() { /* ... */ });
.on is the standard method:
$("#page").on("click", function() {
.......
});
If the p element is generated dynamically, you'll have to do:
$(document).on("click", "#page", function() {
.......
});
Actually, after jQuery 1.7, on is the preferred way to bind events rather than bind. So I prefer on API.
And then:
click(function(){})
is just the shortcut of
on('click',function(){})
Internally, they are actually the same -- when the on param is event, handler, but on is more general because it can do more than simple onClick(example:event delegation) see:link
so I recommend on
Is there a way to automatically unbind all "on" events that were set on an element? I have found a solution but i don't know if it is the corect one.
$(document).off('click', 'li').on('click', 'li', function(e){
e.preventDefault();
// some stuff goes here
});
EDIT:
I have tried all the suggested answers but none worked as i wanted. Maybe it was my mistake that i didn't give enough information: the point is that all my content is loaded dynamically like in tabs and some tabs could be loaded more time.
I have tried this $('li').off().on('click', function(){
});
-> did not work
Also have tried this $('li').unbind().on('click', function(){
});
-> did not work.
You can call .unbind() without parameters to do this:
$('li').unbind();
From the docs:
In the simplest case, with no arguments, .unbind() removes all handlers attached to the elements.
As of jQuery 1.7, off() and on() are the preferred methods to bind and unbind event handlers.
So to remove all handlers from an element, use this:
$('li').off();
or for specific handlers:
$('p').off('click hover');
And to add or bind event handlers, you can use
You can just use unbind() or off() to remove all event handlers from an object.
$('#myNode').unbind();
off() is preferred way to do this in jQuery 1.7+ (noted by #Krishna).
$('#myNode').off();
JSFiddle
$('li').off();//Remove all event handlers from all li elements:
$('li').off('click');//Remove specific event - click
From documentation .off(),
The .off() method removes event handlers that were attached with .on().
From .unbind() documentation,
As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements.
$('li').unbind(); //removes all event handlers
$('li').unbind('click');//removes specific event - click
In jQuery how can I watch a div to determine if it has changed so that I can rebind events and perform some other action as needed?
If the div has dynamic content I would like to tell you about event delegation.
Event delegation allows you to avoid adding event listeners to
specific nodes; instead, the event listener is added to one parent.1
To use event delegation in jQuery you use the on method and provide a selector argument.
You could use DOMSubtreeModified event(see here)
$('my-selector').bind('DOMSubtreeModified', function() {
console.log('Children have been modified');
});
I haven't checked the supported nature of this event but in chrome it works.
Unfortunately : Why is the DOMSubtreeModified event deprecated in DOM level 3?
I'm trying to find the jQuery equivalent of this JavaScript method call:
document.addEventListener('click', select_element, true);
I've gotten as far as:
$(document).click(select_element);
but that doesn't achieve the same result, as the last parameter of the JavaScript method - a boolean that indicates whether the event handler should be executed in the capturing or bubbling phase (per my understanding from http://www.quirksmode.org/js/events_advanced.html) - is left out.
How do I specify that parameter, or otherwise achieve the same functionality, using jQuery?
Not all browsers support event capturing (for example, Internet Explorer versions less than 9 don't) but all do support event bubbling, which is why it is the phase used to bind handlers to events in all cross-browser abstractions, jQuery's included.
The nearest to what you are looking for in jQuery is using bind() (superseded by on() in jQuery 1.7+) or the event-specific jQuery methods (in this case, click(), which calls bind() internally anyway). All use the bubbling phase of a raised event.
As of jQuery 1.7, .on() is now the preferred method of binding events, rather than .bind():
From http://api.jquery.com/bind/:
As of jQuery 1.7, the .on() method is the preferred method for
attaching event handlers to a document. For earlier versions, the
.bind() method is used for attaching an event handler directly to
elements. Handlers are attached to the currently selected elements in
the jQuery object, so those elements must exist at the point the call
to .bind() occurs. For more flexible event binding, see the discussion
of event delegation in .on() or .delegate().
The documentation page is located at
http://api.jquery.com/on/
The closest thing would be the bind function:
http://api.jquery.com/bind/
$('#foo').bind('click', function() {
alert('User clicked on "foo."');
});
One thing to note is that jQuery event methods do not fire/trap load on embed tags that contain SVG DOM which loads as a separate document in the embed tag. The only way I found to trap a load event on these were to use raw JavaScript.
This will not work (I've tried on/bind/load methods):
$img.on('load', function () {
console.log('FOO!');
});
However, this works:
$img[0].addEventListener('load', function () {
console.log('FOO!');
}, false);
You should now use the .on() function to bind events.
$( "button" ).on( "click", function(event) {
alert( $( this ).html() );
console.log( event.target );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button>test 1</button>
<button>test 2</button>
Here is an excellent treatment on the Mozilla Development Network (MDN) of this issue for standard JavaScript (if you do not wish to rely on jQuery or understand it better in general):
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
Here is a discussion of event flow from a link in the above treatment:
http://www.w3.org/TR/DOM-Level-3-Events/#event-flow
Some key points are:
It allows adding more than a single handler for an event
It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
It works on any DOM element, not just HTML elements
The value of "this" passed to the event is not the global object (window), but the element from which the element is fired. This is very convenient.
Code for legacy IE browsers is simple and included under the heading "Legacy Internet Explorer and attachEvent"
You can include parameters if you enclose the handler in an anonymous function