What is the appropriate method to get the already-initialized javascript to interact with content loaded using jQuery's load() method?
Example: You have a table with an onclick event for each row, then append() a new row to the table, suddenly the onclick() event does not fire.
Hopefully it is possible to do this without manually re-initializing every event by writing it into the code that executes the load().
I've looked at $.getScript, live(), and bind() - but haven't gotten any to work. Before I head into hours of trial-and-error, I'd appreciate some guidance.
For the event examples you want .live() or .delegate(), for example:
$("table").delegate("tr", "click", function() {
//do something, the table row is this, for example:
$(this).toggleClass("selected");
});
What this does is attach an event handler to the <table> element, which listens for events to bubble up (which elements do regardless of when they were added) and acts upon those events if the element the event came from matches the selector, in this case a <tr>.
Or it's an element with an unknown parent, use .live() like this:
$(".something").live("click", function() {
$(this).toggleClass("selected");
});
.live() works very similarly (in face .delegate() uses .live() internally), it just attaches to document, so a parent higher in the DOM.
Related
How come the second code better than the first? Why not grab the .vote a directly, instead of grabbing the body tag? I'm creating a voting system using AJAX/JSON/PHP:
$('.vote a').click(function() {});
$('body').on('click','.vote a',function(){});
The second example is a delegated event handler. It is attaching the click event to the body so that it can be applied to any .vote a element which are appended to the DOM after the page has loaded.
You may also see a performance increase from using the delegated model even when there are no elements appended after DOMReady, if there are a lot of elements you need to attach the same event handler to.
That kind of doing is called as event-delegation. And that would be useful when binding events for the elements which are created at run time(dynamically).
I've been doing this to create a handler every time an element is created (rh differs each time, of course):
$('#'+rh).on('click', function (e) {...
I wanted to try to create just one handler for the class rh which will apply to all subsequently created elements in that class. I've tried this, but it hasn't worked:
$('.rh').on('click', function (e) {...
What am I doing wrong? I thought on had a retrospective effect (and the api.jQuery.com site is down).
You should go for a event delegation. As you're creating them dynamically, so you need event delegation (aka, live event) on them.
$('#container').on('click', '.rh', function (e) {...
here #container is the parent of created elements which belongs on DOM at page load. You may have something else.
Read more about .on()
There is another option called .delegate()
$('#container').delegate('.rh', 'click', function (e) {...
I'd go for .on().
How to list events which were bind by jQuery for an element? I tried the methods from this question and none worked.
jsFiddle example
The code you linked to does work, it's just that because you used live() (which is a deprecated function from version 1.7 on), the handler is bound to the top level element, the document, and it uses event bubbling to figure out the original element and see if it matches your selector.
Because you tried to call the $.eventReport() for a specific selector, rather than document, nothing was returned.
If you change live to on, you will see that the alert does show something (jsFiddle). Alternatively, if you omit the selector to $.eventReport() altogether, you will also see that a click event is bound (jsFiddle).
Example for the former:
$(function() {
$('#firstname').on("click", function(e) {
alert('clicked');
});
alert($.eventReport('#firstname'));
});
having a slight problem here. I have a post stream on my site, each post has buttons that execute different actions that are setup in my $(document).ready() now, to add posts I make an AJAX call that returns the html for the new post element, but the actions in the my previous $(document).ready() do not apply to this new element, and adding it in a $(document).ready() for the element causes the buttons from the already posted elements to be duplicated.
Any idea how I can get around this?
The elements that added after documnet ready event don't accept binding events (you call it ations). You may use .click() or .hover() or .bind('click', function(){}) and neither works. You can use jQuery .live() or .delegate()
Using delegate is much better because when you use live for click (for example) it means you'r listening to any click happening on your document and determining if it's that click you where looking for or not? But with delegate you limit the clicks that computer process to find your click.
$('.myinput').live('click', function(){
// do something if a click happened and it was on my input
})
$('.myDiv').delegate('.myinput', 'click', function(){
// do something if a click happened in my div and it was on my input
})
if you use $(selector).live(eventType, handler) it should add events to all elements matching that selector.. even if they are added after the DOM is loaded:
http://api.jquery.com/live/
like #Mohsen said there was a way to solve this using .live()
now its depreciated and there is alternate way:
How to change depreciated method?
$( selector ).live( events, data, handler ); // jQuery 1.3+
$( document ).delegate( selector, events, data, handler ); // jQuery 1.4.3+
$( document ).on( events, selector, data, handler ); // jQuery 1.7+
link: jQuery .live()
I had thesame problem and this last one with ".on" works fine for me.
Maybe someone have thesame problem and use it too
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.