Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

17
  • 14
    Lets say you run the $('#myDiv').click(function(){ code first, then you generate 20 rows of HTML dynamically from JavaScript and each row has a button on it that when clicked the JavaScript is required to execute that same function. If you do that first then it won't work as the event handler has been added before the HTML has been generated. It would seem easier to just throw in the onclick="functionName()" into the dynamically generated HTML then the button works straight away. Or do you know of a more elegant solution for this situation? Commented Sep 27, 2012 at 21:28
  • 18
    @zuallauz for that case jQuery offers .delegate() function. It will attach event to any element that will appear in the future on the site. Commented Sep 27, 2012 at 22:54
  • 18
    @SimonRobb .live is deprecated. Use .delegate for older versions or use .on for newer jQuery versions. Commented Sep 28, 2012 at 0:27
  • 6
    @Vega, Good points. What about readability? Now you have to search all referenced JS files on the page to see all click handlers of an element by element's ID instead of searching for the function name. What's your take on this? Commented Dec 20, 2012 at 6:49
  • 8
    I agree with @supertonsky. I STRONGLY disagree that $('#myDiv').click(function(){ is better. In a large javascript application binding with an event becomes massively difficult to find all the references binding to that target. Is it the binding on a class, an id, a child references to a html tag? And what happens if css changes and class names you bound to need to be changed? In my experience working with others code it becomes very ugly very fast. Commented Jun 26, 2013 at 13:03