In jQuery, should I choose live(), delegate() or on()? - javascript

I've read the jQuery documentation on event handling, but I still can't really understand what I should do.
I have a mobile app where content is loaded with ajax, so events can't be bound at document onLoad for that content.
As my application grow I now start to be concerned that wrong event handling can give performance problem.
What is the implications on performance choosing between on(), live() and delegate() ?
Something else to take into consideration?

From jQuery 1.7, the official (and most performant) way to bind events is .on and .off. It's fastest when combined with an id based selector:
$('#id').on('click', myHandler);
.on supercedes .live .delegate and .bind, see here for more info:
http://blog.jquery.com/2011/11/03/jquery-1-7-released/

Starting with jQuery 1.7, it is recommended that all new code going forward use on() and off() for all event handling.
http://blog.jquery.com/2011/11/03/jquery-1-7-released/

As of jQuery 1.7 the jQuery team/API advise that:
[the] .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
Reference: live() API reference, at: http://api.jquery.com/live/
So the choice, post jQuery 1.7, is between on() and delegate(); and the recommendation, above, seems to suggest that you should use .on() in preference to delegate(). Although I can't argue as to why that is.

In case you're creating a javascript application for yourself or for your own product, you should use jQuery 1.7 and .on() method.
In case you're doing some kind of plugin, which can be used on older versions, I would use .delegate()

Related

jQuery .delegate() and .undelegate() is not working in chrome 56 and above versions

Please let me know the alternate function for this..
$("#_body").undelegate('click').delegate(".class> a",'click',function(){
I want to toggle the portlet on live click.
Thanks
Try on() and off() like:
$("#_body").off('click').on(".class> a",'click',function(){
// your code here
});
Using jQuery on()
In jQuery 1.7, on() method was introduced which is an effort to simplify and merge most event bindings functions into one unified consistent API. If you are interested to see how on() replaces the functionality of all these event methods, open the jQuery 1.7.1 source code (https://github.com/jquery/jquery/blob/1.7/src/event.js#L965) and you will find that bind(), live() and delegate() all point to the on() method.

Jquery .on() native function in javascript

I have created widget which is using jquery latest version 1.11.1.
When i adding my widget into 3rd party website.
And 3rd party website have lower version jquery e.g. 1.5 in my case (it could be any version). 3rd party website jquery don't have the latest function.
e.g
Latest version function
jQuery(document).on("click", function(e) {
...
});
So i am getting error function is undefined. How to resolve this type of issue.
Or did i have created the widgets wrong way that depend on jquery?
If anyone know how to implement java script widget that don't depend on 3rd party library like jquery different version.
If you are using event delegation, only then this answer applies
In jQuery 1.5, you have the .delegate() method, you can use that
$( "table" ).delegate( "td", "click", function() {
$( this ).toggleClass( "chosen" );
});
Don't use .live() as it is removed in verions >= 1.9
The on method is not known in version 1.5
You should use this syntax instead:
jQuery(document).click(function(e) {
...
});
jQuery(document).click(function(e) { here as there is no delegation
And for dynamic HTML use live event as it works in old jquery version and you Must use deprecated syntax as its using old jQuery.
if you have to deal with dynamically data use live()
Jquery .on() is added in version 1.6+. for previous versions you need to use .live()
As you are not delegating the event, you can simply use .click() to attach the click event:
jQuery(document).click(function(e) {
...
});
I don't think there is any direct/dynamic way to resolve your problem.
Even if you resolve the problem with 'click' function. You may face problem with another function which is either not supported in lower version of JQuery or have different syntax/behavior.
e.g. few animations like 'fadeOut(1000)' may not be supported in lower version of JQuery(this is just example. You need to check whether these kind of APIs are supported or not.)
So practically you might have to just do trail and error. Test your JQuery widget/plugin with all available JQuery versions.
You could figure out the Jquery version of the WebSite where you are deploying your widget. See if this is helpful to get the version. https://api.jquery.com/jquery-2/
Depending on version you could use appropriate supported API e.g., live() for v1.5 and below AND .click() for higher versions.
You are good to go when everything works.

Can I use jQuery .trigger() with event listeners added with addEventListener()?

In my (javascript, jQuery) code, I use two ways of firing events
jQuery('body').trigger('crazy-trigger-event');
jQuery("body").get(0).dispatchEvent(new CustomEvent("crazy-dispatch-event"));
In the snippet here:
http://jsfiddle.net/jts9jhbt/3/
I have registered for custom events using both jQuery .on() and the DOM .addEventListener() methods.
Then I fire the events using both jQuery .trigger() and DOM .dispatchEvent() methods.
It seems like the listeners registered using .on() receive events fired both ways.
But the listeners registered with .addEventListener() only receive events fired using .dispatchEvent().
My use case is that I have a mix of legacy code and jQuery code, and it seems like it's safest to use .dispatchEvent() so that it's compatible with both.
So is there some change to the code I can make so that listeners registered with .addEventListener() can recieve events from .trigger() ?
Simple Answer
No, you can't.
Explanation
The main reason is that jQuery needs to work across multiple browsers and ...
"[...] jQuery's event system is a layer on top of the DOM event system."
Eventhough there are exceptions, there is no efficient way for jQuery to know which events are supported by the browser currently due to the lack of a getEventListeners method.
The developers think that the creation of a solution
"[...] isn't possible to do without breaking existing code or causing performance issues."
If that sounds like a challenge to anybody, you are free to prove them wrong by posting your solution.
The detailed explanation can be found in Dave Methvin's answers to jQuery's issue #2476.

Opening all links with class popup in a new window

I have lots of links on my page with class="popup".
I want all of these to open in a new window.
Any nice way to define this with JavaScript?
I am using .live() to support links that might be added later to the DOM. If you are not adding links from event handlers, Ajax callbacks, etc., you can simply use .click().
$('a.popup').live('click', function (e) {
window.open(this.href);
e.preventDefault();
});
Please note, that according to the current HTML5 spec, you can also use:
as you previously could in HTML4. This way, you do not need Javascript. Using target is not recommended though on an XHTML doctype, because it is not considered a valid attribute.
UPDATE: From the jQuery documentation
As of jQuery 1.7, the .live() method is deprecated. Use .on() to
attach event handlers. Users of older versions of jQuery should use
.delegate() in preference to .live().
If you need help changing your code, be sure to check previous StackOverflow questions. Using the SO search [jquery] live deprecated is a good start.
You can put this in your $(document).ready()
$('a.popup').attr('TARGET', '_BLANK');

What is the difference between jQuery live() and liveQuery plugin?

The question says it all. Which one is better and when to use what, I never use jQuery live() as I am using liveQuery plugin for a couple of years, I am used to it and still continue using it. But I want to know the subtle differences between the two and when to use each of it?
The "live" function native to jQuery leverages the bubbling of events up the DOM. The "liveQuery" plugin, by contrast, uses the selector to find elements in the DOM and attach event handlers directly.
In my opinion you're way better off using the "live" function when possible, because it involves less DOM traversal etc. For example, hooking event handlers to things throughout a big table can be kind-of slow with liveQuery but not slow at all with "live". There may be some issues (with IE of course) that force you to use liveQuery sometimes, though jQuery 1.4 has improved "live" considerably.
edit — Update: Sep 2017
At this point, modern versions of jQuery centralize event handler registration in the .on() API. Briefly:
$(selector).live("event-name", handler);
would today be written with .on():
$(document).on("event-name", selector, handler);
The .on() API provides considerably more flexibility than the long-deprecated .live() method did, including the option of using any node in the DOM as the delegation point (like the old .delegate() did).
As Pointy said, live() leverages the bubbling of events up the DOM (event delegation).
Also, for each $(selector).live(type, handler) call, jQuery only calls handler on the $(event.target).closest(selector) element - that is, the nearest matching ancestor-or-self element of the event target.
And, of course, live() doesn't support anything like livequery( matchedFn, unmatchedFn ).
Implications:
$(selector).live() still requires a traversal of the DOM (obviously).
However, if you load jQuery and attach live() handlers in the document head then there is no document body to search yet. Similarly if you insert new content into the page.
live() does less work when being configured - it doesn't have to attach handlers to every matched element
live() does more work in handling events - it has to traverse ancestors of the event target, finding elements that match the selector
$("div").live() is different to $("div").livequery() as it only works for the closest div to the event target
Similarly, $("div, p").live() is different to $("div").live(); $("p").live();
liveQuery plugin was created initially, and then was migrated to jQuery itself.
One of the differences is that .live() is native to jQuery (http://api.jquery.com/live/) and .livequery() is a plugin. As you can see at http://api.jquery.com/live/, .live() was deprecated in jQuery 1.7, and removed in version 1.9.

Categories

Resources