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);
Related
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
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');
});
Not sure if this is posible or not, but I'm trying to use JavaScript that I loaded via a script tag when the page was initially requested on dynamic HTML that was loaded via jQuery's load() function.
Example: http://jsfiddle.net/3MR43/
As you can see in the example, after clicking a link in the pop up box, the link goes. The problem is that the link was suppose to be stopped, and you were suppose to see an alert.
However, if I paste the HTML that I am loading via jQuery, it works, so the code is fine.
Description
You need jQuery .live() or .on() method to bind events to dynamically created html.
Choose .live() or .on() depending on the version of jQuery you are using.
.live() Available since jQuery 1.3. Attach an event handler for all elements which match the current selector, now and in the future.
.on() Available since jQuery 1.7. Attach an event handler function for one or more events to the selected elements.
Check out my sample and this jsFiddle Demonstration
Sample
... for jQuery.live()
$('.lang').live("click", function(e) {
e.preventDefault();
alert('Testing..');
});
... for jQuery.on()
$('.lang').on("click", function(e) {
e.preventDefault();
alert('Testing..');
});
More Information
jsFiddle Demonstration
jQuery.live()
jQuery.on()
The problem is your .click will do it for only elements that exist at that time. If you want to do it for all potential future elements that that selector will match, you want to use on() (delgate() or live() with older versions of jQuery).
The $('.lang').click() event must be registered after the element is created!
You need a callback on the load function to register this.
You need to use live to attach handlers to elements that are loaded dynamically.
Try this, it will solve your problem.
$('.lang').live('click',function(e) {
e.preventDefault();
alert('Testing..');
});
You have to use on function for dynamicly loaded elements:
$('.open_lang').click(function(e) {
e.preventDefault();
$('#popup').load('http://skins.thehabbos.org/pop_up/language.php').css('display', 'block');
});
$('body').on('click', '.lang', function(e) {
e.preventDefault();
alert('Testing..');
});
(live and delegate are deprecated in JQuery 1.7+ which is the version of your JSFiddle)
Fixed JSFiddle
I am facing problem while unbinding the event using JQuery.
$(document).ready(function() {
$('#tdMinPriceOnNonStop0').unbind("click");
});
Its Not Working..
<td class="tddat matrixCellHt" align="center" onclick='javascript:DoHighlighting("tdMinPriceOnNonStop",<%#Container.ItemIndex%>);FilterResults("SingleAirlineParticularStop","0&<%#((string)DataBinder.Eval(Container.DataItem, "AirlineDisplayName"))%>")' id="tdMinPriceOnNonStop<%# Container.ItemIndex %>"
It's not obligatory, but you should provide the handler you wish to unbind:
function doStuff(){
//doing stuff
}
$('#tdMinPriceOnNonStop0').bind("click",doStuff);
//then
$('#tdMinPriceOnNonStop0').unbind("click",doStuff);
go for
$('#tdMinPriceOnNonStop0').removeProp("onclick").removeAttr("onclick");
Because the event handler is stored directly in the element's property rather than in jQuery's $.data object (where jQuery stores all its handlers) you can't use jQuery's unbind method (removeProp removes the compiled handler. removeAttr isn't strictly necessary, but it removes the actual attribute (the string "javascript: ... ") too for greater consistency.
you can unbind() handlers you only previously attached with bind()(with jQuery 1.7+ you should use respectively off() and on()
If this is not the scenario just simply destroy any click handler defined for that element in plain javascript
$(document).ready(function() {
document.getElementById('tdMinPriceOnNonStop0').click = function() { };
});
I am trying to use SimpleBox jQuery plug-in on my website. I have the code such that everytime the user clicks on a div of class "link", a SimpleBox is invoked.
I also have another button that uses javascript to dynamically create divs of class "link" to my page. However, when I try to click these divs, the SimpleBox is not invoked.
<script type="text/javascript">
function createLinkDiv()
{
var parentDiv = document.getElementById ("right");
var linkDiv = document.createElement("div");
numDivs++;
linkDiv.setAttribute("class","link");
linkDiv.setAttribute("id",numDivs);
parentDiv.appendChild(linkDiv);
}
$().ready(function() {
$(".link").click(function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
$(".close_dialog").click(function() {
event.preventDefault();
$("#simplebox").simplebox('close');
});
});
</script>
Any idea why? Any help would be appreciated! Thanks!
For Dynamically added items use .live() or .delegate() to attach event handlers
$(".link").live("click",function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
Or
$("#right").delegate(".link","click",function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
Out of context
I suppose you've placed the the createLinkDiv function since you're calling it through inline javascript. Calling functions via inline javascript is a bit of out of fashion these days. Binding those events in code helps to keep your javascipt code easily maintainable.
$("#createLink").click(function(){
$('<div/>').attr({"class":"link","id":"link_" + $(".link").size() })
//Id shouldn't start with a number (not in HTML5)
.click(linkClick)
//Now you don't have to use live
.appendTo("#right");
});
As a side note, the $().ready() syntax is deprecated; it's better to use $(document).ready or just call $ with a function as a parameter.
To answer your main question, the .click method only binds to elements that exist when it's called. So when you add elements to the DOM later, you're not launching the simplebox on click because the handler hasn't been bound. You could either use .delegate to attach event handlers, or you could add the onclick directly in the creation of the DOM element.
The accepted answer is out of date now. The live() method has been removed from jQuery 1.9 and replaced with the on() method.
The syntax for on() is
$(element).on(event, selector, handler)
So in #jnfr's case, one of his handlers could be re-written as
$(document).on("click",".link",function(event) {
event.preventDefault();
$("#simplebox").simplebox();
});
Hopefully this will be of use to anyone arriving here and getting errors when using live().