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.
Related
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
Besides click, mouseover, and mouseleave, are there any other events for jQuery's on() function or are those the main uses for on()? I can't find any documentation on it.
You can use built-in DOM events or you can create your own events. Here's a list of some of the built-in DOM events (all events don't occur on all types of objects):
click
dblclick
mousedown
mouseup
mouseover
mousemove
mouseout
keydown
keyup
keypress
load
unload
abort
error
resize
scroll
select
change
submit
reset
focus
blur
focusin
focusout
touchstart
touchend
touchmove
touchenter
touchleave
touchcancel
cut
copy
paste
beforecut
beforecopy
beforepaste
contextmenu
drag
dragstart
dragenter
dragover
dragleave
dragend
drop
selectstart
beforeunload
readystatechange
beforeprint
afterprint
See http://en.wikipedia.org/wiki/DOM_events for a decent description of most of these.
on() can be used for anything. It is just a way to delegate events to a specific DOM element.
Check out: http://api.jquery.com/on/
It will tell you how to "convert" bind, live, delegate functions into the new "on" method.
In addition to Parris anwser you can do
$("#whatever").on("my.awesome_event", function(event, one, two, three){
// stuff ...
});
$("#whatever").trigger("my.awesome_event", [1,2,3]);
In this example variables one, two, three will have values 1, 2, 3.
You could use any built in events (change, focus, mousedown, blur, touchstart, etc...) or you can make your own events and bind them even!
I use jQuery's on for both built-in DOM events such as change, click, blur, etc. and my own custom events within classes. For most classes I want custom events for, I will do this:
this.events = $({});
I can then bind custom events like this:
foo.events.on("myCustomEvent", function(e) {
// Do something
});
And I can trigger like this:
this.events.triggerHandler("myCustomEvent");
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.
Recently , Ive been using .delegate and .live a lot.They have a subtle difference when it comes to event capturing I guess.
When using live for link clicks like $('a').live("click",... , the links which had an image as their html content, ended up with the click handler getting the target as the image instead of the link.
Whereas with delegation ,it seems that it the link which is passed as the target.
What is the catch here?
Also, when exactly is a click handler called for .delegate, while the capturing phase or the bubbling phase?
The main difference between .live and .delegate is, that .delegate() uses a context. In other words, .delegate() is actually a wrapper for .live(), but instead watching the document root for bubbling events, it'll just watch a given root node.
For instance
$('a').live('click', function() {
});
will create an event handler attached to your document.body. This will catch absolutly all anchors-clicks that occur on your site.
$('#someDiv').delegate('a', 'click', function() {
});
will only "watch" all anchors which are childnodes from #someDiv.
It's unlikely that a delegated event by .live() have another target. Both .live() and .delegate() pass in the event object into the handler. It should make no difference at all, the event.target should always be the node of invocation.
Ref.: .live(), .delegate()
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