-1

I have a button which is dynamically added on the page (via mustache).

There is a class on it.

But when I click on this button, the JQuery method is not executed.

My HTML:

<div id="layout"></div>

My HTML with the dynamically added button:

<div id="layout">
    <a href="#" class="hello">Hello</a>
</div>

My jQuery:

$(function(){
    $('.hello').on('click', function(e){
        e.preventDefault();
        console.log('Hello');
    });
});
Ganesh Gaxy
  • 657
  • 5
  • 11
Michael T.
  • 187
  • 1
  • 10

1 Answers1

1

You can't use on() on elements that dont exist, asign them to the first wrapper that exists (ideally an id), and use another parameter to tell jQuery to look for the class in the selector:

$('#layout').on('click', '.hello', function(e){ /* ... */ });

"Can't I just add everything to document?"
Yes you could, but you shouldn't. Everytime you click on something, it goes up the DOMtree:
1. You click a button, it fires the click event
2. while there is a parent, trigger the click event for the parent aswell
3. After you did the last (document), stop.

As you can see, step 2 could be a heavy step if you have lots of html. Binding events as 'local' as possible is the prefered method.

Martijn
  • 15,791
  • 4
  • 36
  • 68