Skip to content

Instantly share code, notes, and snippets.

@hsuh
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hsuh/44f653724c51693c093b to your computer and use it in GitHub Desktop.
Save hsuh/44f653724c51693c093b to your computer and use it in GitHub Desktop.
Biding events to dynamically created html elements
Here is what gets you all the way:
$(document).ready(function() {
$(document).on("click","textarea",function(){
// Do something when textarea is clicked
});
});
If your app is like most web apps, it is probably full of AJAX. Suppose you have a page that renders some buttons or links but it also dynamically adds more of those elements as events happen, such as an AJAX pagination event. To top it off, all those elements have events tied to them (think hitting "Like" on a friends Facebook post that was not initially visible on the page.").
How do you handle events for any of those links, regardless when they show up in the DOM?
The standard way works...partially:
$(".awesome-button").on("click", function(e) {
// do awesome and blow your mind
// Uh oh. Doesn't work for dynamically added elements
});
//textarea could be dynamically created based on some Ajax
//http://www.go4expert.com/articles/bind-jquery-events-dynamically-created-t29931/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment