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
Related
I have come across several methods for handling click events in jquery:
bind:
$('#mydiv').bind('click', function() {
...
});
click:
$('#mydiv').click(function() {
...
}
on:
$('mydiv').on('click', function() {
...
}
Two questions:
Are they any other ways of doing this?
Which one should I use, and why ?
UPDATE:
As eveyone has helpfully suggested, I should have read the docs better, and found out that I should use:
on() or click(),
which are effectively the same thing.
However, nobody has explained why bind is no longer recommended ? I'll probably get more downvotes for missing the obvious somewhere, but I can't find a reason for this in the documents.
UPDATE2:
'on' has the useful effect of being able to add event handlers to dynamically created elements. e.g.
$('body').on('click',".myclass",function() {
alert("Clicked On MyClass element");
});
This code adds a click handler to elements with a class of 'myClass'. However, if more myClass elements are then dynamically added later, they automatically get the click handler as well, without having to explicitly call 'on'. From what I understand people are saying, this is also more efficient (see Simons answer below).
From the documentation of bind and click :
bind :
As of jQuery 1.7, the .on() method is the preferred method for
attaching event handlers to a document.
The source makes it clear there's no reason to use bind, as this function only calls the more flexible on function without even being shorter :
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
So I'd suggest, just like the jQuery team, to forget the old bind function, which is now useless. It's only for compatibility with older code that it's still here.
click :
This method is a shortcut for .on('click', handler)
This shortcut is of course less powerful and flexible than the on function and doesn't allow delegation but it lets you write a shorter and, arguably, slightly more readable, code when it applies. Opinions diverge on that point : some developers argue that it should be avoided as it is just a shortcut, and there's also the fact that you need to replace it with on as soon as you use delegation, so why not directly use on to be more consistent ?
To your first question: there's also .delegate, which was superseded by .on as of jQuery 1.7, but still is a valid form of binding event handlers.
To your second question: You should always use .on like the docs say, but you should also pay attention on how to use .on, because you can either bind the event handler on an object itself or a higher level element and delegate it like with .delegate.
Say you have an ul > li list and want to bind a mouseover event to the lis. Now there are two ways:
$('ul li').on('mouseover', function() {});
$('ul').on('mouseover', 'li', function() {});
The second one is preferable, because with this one the event handler gets bound to the ul element once and jQuery will get the actual target item via event.currentTarget (jQuery API), while in the first example you bind it to every single list element. This solution would also work for list items that are being added to the DOM during runtime.
This doesn't just work for parent > child elements. If you have a click handler for every anchor on the page you should rather use $(document.body).on('click', 'a', function() {}); instead of just $('a').on('click', function() {}); to save a lot of time attaching event handlers to every element.
I think that you should have searched the jquery docs before posting this question :
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
I am using a library that when complete will trigger an event via $(document).trigger('playlistDone');. I am listening to this trigger but I am not getting the alert() I am expecting.
$(document).bind('playlistDone', function() {
alert('done');
});
What am I doing wrong?
First off, as of jQuery 1.7 the preferred method for attaching events is on, not bind (see http://api.jquery.com/on/).
Second, your basic syntax looks ok, but it's important to understand you're dealing with custom events, not browser events. This means that your library must be using jQuery to trigger its event, or else jQuery won't detect it when it happens.
Use .on(). From jQuery documentation :
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.
Try something like that:
$(document).on('playlistDone', function( a ) {
alert( a );
});
and
var data = 'Done';
$(document).trigger('playlistDone', data );
I am trying to bind click handlers to incoming ajaxed content. I used to use 'live'
$('#div').live('click', function(event) {
alert('I got clicked, Live style');
});
But now as my site is getting more complicated, I am realizing how crazy things can get using live and having everything bubble to the top of the DOM. Which is not ideal.
So I started using on(),
$('#div').on('click', function(event) {
alert('I got clicked, On style');
});
But I miss the fact that using live() I could just initialize the click handlers once and be done with it instead of reinitialize them every time new content is loaded. Is there a best of both worlds?
Is there a better way to "reload" click handlers to recognize new ajax content aside from creating the handlers in the ajax callback function? To me that seems highly suspect. Whats the appropriate way to do this?
As of jQuery 1.7 the following .on() event binding is equivalent to the deprecated live:
$(document).on('click', '#div', function(event) {
alert('I got clicked, On style');
});
You can also bind the event to some fixed element further down the DOM which doesn't get re-generated, this functionality would be the same as .delegate():
$('#parentofdiv').on('click', '#div', function(event) {
alert('I got clicked, On style');
});
It is advisable to use the second form to narrow down the scope of the event binding as much as possible to make it easier to maintain.
Edit: For the record, what you originally did in your post would be the preferred replacement for your .bind() calls in your code.
Have you looked at using .delegate? http://api.jquery.com/delegate/
jQuery's on() method can be used to attach various events to already existing items as well as items added by ajax calls to the DOM in the future:
$(document).on("click", ".ajax-added-content", function(event) {
alert('I got clicked, On style');
});
It is possible to do what you want with
.on()
and it is actually the recommended method.
.live()
is deprecated as of jquery 1.7.
You can attach your event to the body and use this overload of "on" to get the functionality you desire. Check the next to last example in jquery's doco of .on
$("body").on("click", "#div", function(){
alert('I got clicked, On style');
});
I have an group of checkboxes with id's starting with somename and I want catch the click event of these checkboxes. Previously I have done this through jQuery. i.e.:
$("input[id^='somename']").click(function(){
// my code follows here
})
but this is not working this time around. Why?
P.S. The element is created via JavaScript after the page is fully loaded after making some ajax request. I don't know if this may be the problem?
just use live if elements are created after the page is loaded.
$("input[id^='somename']").live('click', function(){ // my code follows here })
P.S : Your search selector is "somename" but you search it on the attribute ID, are you sure that you don't want :
$("input[name^='somename']").live('click', function(){ // my code follows here })
instead?
This indeed could be the problem. Replace .click with .live()
$("input[id^='somename']").live('click', function(){ // my code follows here })
and you should be fine.
Since a call to .click is just a shortcut for .bind('click', fnc), this will not work if the element is not in the DOM when calling this. Even better than using .live() would be to use .delegate(). Have a read:
.live(), .delegate()
Using the standard binding functions only works on elements that exist at the time of the bind. You need to use something called event delegation, where elements further up the DOM tree are notified of events on descendant elements. The best way to do this is with .delegate():
$('#containingElement').delegate("input[id^='somename']", 'click', function(){
// your code here
});
This assumes that you have an element #containingElement that contains all the elements that you want to capture the events on.
NB that other answers recomment live. live and delegate use the same backend code, but for various reasons delegate is more efficient.
I believe that because you want this applied to dynamically created elements in the DOM you are going to have to use the the jQuery .live() method:
$("input[id^='somename']").live('click', function(e) {
// Your code
});
Instead of .click() try .change() event.
i have a code that bind's on click action on page load, it is a link. When i clicking it, it send ajax request and replace content in some div with jquery append() function. This new content has a links and i need to bind some action for them, but i could't.. bind did't work i think, because jquery append doesn't update DOM tree. How could i get a late binding?
There are 3 functions that can do this:
$(selector).live(events, data, handler); - jQuery 1.3+ - version deprecated: 1.7, removed: 1.9 (reference)
$(document).delegate(selector, events, data, handler); - jQuery 1.4.3+ - As of jQuery 1.7, .delegate() has been superseded by the .on() method. (reference)
$(document).on(events, selector, data, handler); - jQuery 1.7+ - preferred (reference)
It's generally adviced to use on() and it's use is simple and probably preferred way.
The first selector must exist when calling the function and may not be deleted or the event will be gone too (this can be document).
The first parameter is the event (e.g. "click")
The second parameter is the selector of which you want to bind the event on.
Then finally you can add some custom data and a function to the event.
Here's some sample code:
// Make sure the DOM is ready
$(function() {
// Bind the click event to the function
$(document).on("click", "a.class", function(event) {
// Put your code here.
});
});
Late binding is now available by utilizing jQuery's live() event:
$('a.my-links-class').live('click', function() {
// do your link action here
});
Method .live in JQuery 1.9 is deprecated.So now u can do like this:
$("body").on("click", ".classname", function() { ... })
the .live() event was deprecated from verions 1.9 up.
For anyone using later version of Jquery they can use the .on() event, it works pretty much in the same way.
You need to use jQuery's live function, which will bind an event to all elements that match a selector, no matter when they were created.
You can use jQuery 1.3+'s $().live(event, function) function. $("a").live("click", myClickFunc) will bind myClickFunc just like $("a").click(myClickFunc) or $("a").bind("click", myClickFunc), but the events will be bound "live", so elements that are added to the DOM after that function call will also be bound.
You can remove live-bound events with $().die().
For more information on $().live, see the documentation for it.
Another option would be to have a function to bind the elements given a certain context (using the $ selector function's rarely-used second parameter):
function myBindEvents(context) {
$("a", context).click(myClickFunc);
}
and call that whenever you update an element with AJAX:
$("<div>").load("...", "...", function(){myBindEvents(this);});
Hope this helps. :)
In my case I am using js library in that I have element variable and code was like
$(element).click(function(){
//some action
});
but that is not working with my late binding element.
So I finally use core js click event
element.addEventListener('click', function() {
//My some action
}, false);