Consider the following:
var template = '<div class="dynamic">Some markup</div>'
, $template = $(template);
$template.on('click.namespace.data-api', function(e) { doStuff() });
$('div.#parent').append($template);
To me, this seems to be the most optimal way to bind an event to a node, since the event is attached to a node that has already been introduced as a jQuery object. However, I'm not sure how this plays out during actual click events; on click, is jQuery able to find this element immediately since the event is bound to a jQuery object? Or is it more optimal to bind the event using something like:
var template = '<div class="dynamic">Some markup</div>'
, $template = $(template);
$('div.#parent').append($template);
$('div.#parent').on('click.namespace.data-api', 'div.dynamic', function(e) { doStuff() });
JQuery objects only persist in the exact call they are in. As soon as that call is done the object no longer is related as a JQuery object.
As you are showing with click delegation you wont have to worry about the dynamic aspect of the element being created at any moment, because the handler is hooked to the parent node, then watches for click on the delegated element/class.
Writing the second version of click delegation using the direct delegation method to me is much easier to read, and is more clear when you come back to read again in the future.
Instead of binding event to the specific element, you can bind it to document instead.
`$('.dynamic').click()` can be replaced with `$(document).on('click', '.dynamic', function())`
Related
I have a jQuery plugin, and inside of it I have an init function. Inside of this init-function I attach some events:
(function ( $ ) {
$.fn.gallery = function(options) {
var init = function(self) {
var main += '<input id="gallery-search">';
//click event for the filter checkboxes
$("body").on('click', self.selector+" .gallery-filter-checkbox",function(event) {
self.data(filter( self ));
});
//capture input in the search box
$('#gallery-search').keyup(function(){
console.log('test');
});
self.html(output);
}
}( jQuery ));
}
The first one works just fine, but the second one doesn't work at all. I have tested it outside of the plugin scope and it works just fine so there is no syntax error, but probably an error in the way I try and attach the event?
Since #gallery-search is created dynamically, you can use delegated event handler:
$(document).on('keyup', '#gallery-search', function() { ... });
If self represents static HTML element at page, you can use a little better (for performance) version:
self.on('keyup', '#gallery-search', function() { ... });
Or you can place event handler in code after element's insertion, if HTML will not be modified later:
self.html(output);
$('#gallery-search').keyup(function()
{
console.log('test');
});
keyup() is a shortcut for bind('keyup',callback) which will register some event handler on the elements that are already present in the DOM (not necessarily rendered). It won't work if the element is not present in DOM when it's defined. To do that you need to use delegate() which will attach some handler on an element which is currently available or in might be available in future.
From jQuery 1.7 onwards, it's recommended to use on() as it combines the functionality of bind / delegate / live.
on() can be used in two ways
$(selector).on('event',callback);
$(parentSelector).on('event','someChildSelector', callback);
First one is direct handler and second one is called delegated handler.
If you're using first one to register event handlers, you've to make sure that element is present in the DOM at the time of registering just like bind(). So if you're adding new elements, you have to attach that handler again.
If you're using the second way, you don't have to worry about registering the handler again
$(document).on('click','.row',callback);
As document is always available, you callback will be registered as click handler for all the existing rows and any new row that you might add in the future.
I strongly recommend you read the Direct and delegated events section here. They even explain about the performance benefits.
Now that you know how it works, you can fix it using on() either as a direct handler or as a delegated handler.
EDIT : It's better to use closest static parent than document/body when using on() to register delegated handlers. Thanks to Regent for suggesting that :)
$('closestStaticParent').on('keyup','#gallery-search',function(){
console.log('test');
});
I have the following code:
var $reviewButton = $('span.review_button');
$reviewButton
.live('click',
function(){
$('#add_reviews').show();
}
)
Later in the script, I use an AJAX call to load some content and another instance of $('span.review_button') enters the picture. I updated my code above to use '.live' because the click event was not working with the AJAX generated review button.
This code works, as the .live(click //) event works on both the static 'span.review_button' and the AJAX generated 'span.review_button'
I see however that .live is depracated so I have tried to follow the jquery documentations instructions by switching to '.on' but when I switch to the code below, I have the same problem I had before switching to '.live' in which the click function works with the original instance of 'span.review_button' but not on the AJAX generated instance:
var $reviewButton = $('span.review_button');
$reviewButton
.on('click',
function(){
$('#add_reviews').show();
}
)
Suggestions?
The correct syntax for event delegation is:
$("body").on("click", "span.review_button", function() {
$("#add_reviews").show();
});
Here instead of body you may use any static parent element of "span.review_button".
Attention! As discussed in the comments, you should use string value as a second argument of on() method in delegated events approach, but not a jQuery object.
This is because you need to use the delegation version of on().
$("#parentElement").on('click', '.child', function(){});
#parentElement must exist in the DOM at the time you bind the event.
The event will bubble up the DOM tree, and once it reaches #parentElement, it is checked for it's origin, and if it matches .child, executes the function.
So, with this in mind, it's best to bind the event to the closest parent element existing in the DOM at time of binding - for best performance.
Set your first selector (in this case, div.content) as the parent container that contains the clicked buttons as well as any DOM that will come in using AJAX. If you have to change the entire page for some reason, it can even be change to "body", but you want to try and make the selector as efficient as possible, so narrow it down to the closest parent DOM element that won't change.
Secondly, you want to apply the click action to span.review_button, so that is reflected in the code below.
// $('div.content') is the content area to watch for changes
// 'click' is the action applied to any found elements
// 'span.review_button' the element to apply the selected action 'click' to. jQuery is expecting this to be a string.
$('div.content').on('click', 'span.review_button', function(){
$('#add_reviews').show();
});
I have a target div el with some components displayed. These components have some events attached (on mouse over, on click). I don't control this code neither those events. They are just there. I'd like to render a widget inside this div. To do so I'm doing something like:
var save = el.innerHTML;
el.innerHTML = "my widget code";
When my widget finishes its process I want to get back to the original content so I do:
el.innerHTML = save;
The components previously saved are correctly replaced but the events attached to them don't work anymore.
I can't hide, show divs. I need to replace the innerHTML to have the exact style and positioning.
What would you do in my case?
I'm using jQuery if it helps.
Thanks.
When you serialize DOM elements back to HTML, all the event handlers and bound data are lost.
If you have DOM, work with it, not with HTML:
var save = $(el).children().detach();
$(el).html(widgetHTML);
// later
$(el).empty().append(save);
You might find .detach useful - http://api.jquery.com/detach/
It does the same as .remove but keeps all the associated jquery element data - which will include any event listeners added with jquery, though you will lose any 'regular dom events' attached.
you'd have to re-attach the element with jQuery too:
var stored = $(el).detach();
//… wait for something to finish, then reattach
stored.appendTo('#outer');
You can delegate the event to your el element since it doesn't seem to change - Those newly added elements did not exist at the time of binding
$(el).on('click','yourelementtoattachevent',function(){
// replace click with your event/events
// your code goes here
});
This is assuming you are using jQuery 1.7+, for others use
$(selector).live(); // jQuery 1.3+
$(document).delegate(selector, events, handler); // jQuery 1.4.3+
$(document).on(events, selector, handler); // jQuery 1.7+
As Jquery Mobile keeps some pages in the DOM when navigating around, a page may be visited multiple times when going back and forth.
If I'm binding to a page like below and inside this binding perform all my page logic, which includes "nested element bindings":
// listener for the page to show:
$(document).on('pagebeforeshow.register', '#register', function() {
// stuff
// page event bindings:
$(document).on('click.register', '.registerSubmitter', function(e) {
// do something
});
});
Going back and forth causes my nested binding to be attached multiple times.
Right now trying to work around this like so (doesn't work...):
$(document).on('click', '.registrySubmitter', function(e) {
if ( $(this).attr('val') != true ) {
$(this).attr('val') == true;
// do something
}
});
So I'm only allowing the first binding to pass and then I block every other binding attempt that comes along.
While this works, it's far from optimal.
Question:
How and when should event bindings be properly unbound/offed? Is there a general way (kill all) or do I have to do this binding per binding? Maybe more importantly: Is it better performance-wise to do a binding once and keep it or bind/unbind when the user comes to/leaves the page?
Thanks for input!
EDIT:
So I'm namespacing all my events and then listen for pageHide like so:
$(document).on('pagehide.register', '#register', function(){
$(document).off('.registryEvents');
});
While this seems to unbind, it also fires when ever I close a custom dialog/selectmenu on the page, so I'm loosing my bindings before leaving the page. So partial answer, I should use off(), but how to bind to the page really being left vs. opening and closing a select menu?
When you use .on() like that, you are delegating the event handling to the document element, meaning you can setup that delegated event binding anytime you want because the document element is always available.
I've got two suggestions:
Use the pageinit or pagecreate event to only run the page-specific bindings when pages are added to the DOM and initialized. Using this method I would not delegate the event bindings within the pageinit or pagecreate event handlers because when they fire, all the elements on the pseudo-page are in the DOM:
.
$(document).on('pageinit', '#register', function() {
//note that `this` refers to the `#register` element
$(this).find('.registerSubmitter').on('click', function(e) {
// do something
});
});
Bind the delegated event handlers once and don't worry about when pages are actually in the DOM:
.
//this can be run in the global scope
$(document).on('click.register', '.registerSubmitter', function(e) {
// do something
});
Basically when you bind an event using delegation like you are, the actual CPU hit of adding the event handler is less but each time an event is dispatched (of any kind that bubbles) it has to be checked if it matches the delegated event handler's selector.
When you bind directly to elements it generally takes more time to do the actual binding because each individual element has to be bound to rather than binding once to the document element like with event delegation. This however has the benefit that no code runs unless a specific element receives a specific event.
A quick blurb from the documentation:
Triggered on the page being initialized, after initialization occurs.
We recommend binding to this event instead of DOM ready() because this
will work regardless of whether the page is loaded directly or if the
content is pulled into another page as part of the Ajax navigation
system.
Source: http://jquerymobile.com/demos/1.1.0/docs/api/events.html
I am using jQuery v.1.7.1 where the .live() method is apparently deprecated.
The problem I am having is that when dynamically loading html into an element using:
$('#parent').load("http://...");
If I try and add a click event afterwards it does not register the event using either of these methods:
$('#parent').click(function() ...);
or
// according to documentation this should be used instead of .live()
$('#child').on('click', function() ...);
What is the correct way to achieve this functionality? It only seems to work with .live() for me, but I shouldn't be using that method. Note that #child is a dynamically loaded element.
Thanks.
If you want the click handler to work for an element that gets loaded dynamically, then you set the event handler on a parent object (that does not get loaded dynamically) and give it a selector that matches your dynamic object like this:
$('#parent').on("click", "#child", function() {});
The event handler will be attached to the #parent object and anytime a click event bubbles up to it that originated on #child, it will fire your click handler. This is called delegated event handling (the event handling is delegated to a parent object).
It's done this way because you can attach the event to the #parent object even when the #child object does not exist yet, but when it later exists and gets clicked on, the click event will bubble up to the #parent object, it will see that it originated on #child and there is an event handler for a click on #child and fire your event.
Try this:
$('#parent').on('click', '#child', function() {
// Code
});
From the $.on() documentation:
Event handlers are bound only to the currently selected elements; they
must exist on the page at the time your code makes the call to .on().
Your #child element doesn't exist when you call $.on() on it, so the event isn't bound (unlike $.live()). #parent, however, does exist, so binding the event to that is fine.
The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent from #child.
$(document).on('click', '.selector', function() { /* do stuff */ });
EDIT: I'm providing a bit more information on how this works, because... words.
With this example, you are placing a listener on the entire document.
When you click on any element(s) matching .selector, the event bubbles up to the main document -- so long as there's no other listeners that call event.stopPropagation() method -- which would top the bubbling of an event to parent elements.
Instead of binding to a specific element or set of elements, you are listening for any events coming from elements that match the specified selector. This means you can create one listener, one time, that will automatically match currently existing elements as well as any dynamically added elements.
This is smart for a few reasons, including performance and memory utilization (in large scale applications)
EDIT:
Obviously, the closest parent element you can listen on is better, and you can use any element in place of document as long as the children you want to monitor events for are within that parent element... but that really does not have anything to do with the question.
The equivalent of .live() in 1.7 looks like this:
$(document).on('click', '#child', function() ...);
Basically, watch the document for click events and filter them for #child.
I know it's a little late for an answer, but I've created a polyfill for the .live() method. I've tested it in jQuery 1.11, and it seems to work pretty well. I know that we're supposed to implement the .on() method wherever possible, but in big projects, where it's not possible to convert all .live() calls to the equivalent .on() calls for whatever reason, the following might work:
if(jQuery && !jQuery.fn.live) {
jQuery.fn.live = function(evt, func) {
$('body').on(evt, this.selector, func);
}
}
Just include it after you load jQuery and before you call live().
.on() is for jQuery version 1.7 and above. If you have an older version, use this:
$("#SomeId").live("click",function(){
//do stuff;
});
I used 'live' in my project but one of my friend suggested that i should use 'on' instead of live.
And when i tried to use that i experienced a problem like you had.
On my pages i create buttons table rows and many dom stuff dynamically. but when i use on the magic disappeared.
The other solutions like use it like a child just calls your functions every time on every click.
But i find a way to make it happen again and here is the solution.
Write your code as:
function caller(){
$('.ObjectYouWntToCall').on("click", function() {...magic...});
}
Call caller(); after you create your object in the page like this.
$('<dom class="ObjectYouWntToCall">bla... bla...<dom>').appendTo("#whereeveryouwant");
caller();
By this way your function is called when it is supposed to not every click on the page.