plonknimbuzz
plonknimbuzz

Reputation: 2664

What is different between $(document).on() and $(element).on()

I know about jquery .on() use and purpose, because I use it.

But I want to know what is the difference between $(document).on() vs $(element).on() in this script:

<html>
...
<body>
...
  <table id="table-user">
    <thead>...</thead>
    <tbody>
      AJAX DYNAMIC CONTENT
    </tbody>
  </table>
....
<script>
  $(document).on('click','.btn-edit',function(){
    go_edit();
  });

  $('#table-user').on('click','.btn-edit',function(){
    go_edit();
  });

</script>
</body>
</html>

is any performance different or something else between them?

Upvotes: 23

Views: 53591

Answers (3)

Mooze
Mooze

Reputation: 536

What if the Node doesn't exist in the DOM.

Consider the case when the node whose events you want to listen does not yet exist in the DOM. Then $(document).on('event', 'child-selector', callback); proves very helpful.

Upvotes: 5

Yeasir Arafat Majumder
Yeasir Arafat Majumder

Reputation: 1264

Main difference is already answered by @Mukesh. I will try to add one more thing.

When you click(or any other event) on an element(like div or button) in the html document, that clicking event is propagated to the parent elements of that element. So if you have structure like this:

<div>
    <table>
        <tr>
            <td>
                <button>Click Me</button>
            </td>
        </tr>
    </table>
</dvi>

and you click on the button, that click will propagate to the td, then to the tr, then to the table and then finally to the document itself.

Now lets say you have registered a click event on the document($document.on('click',...)) and also on the button($(button.on('click',...))), both of which does some different actions. Then if you click on the button, the corresponding button action will be executed, and also the corresponding action of the $(document) will also be executed.

To prevent the button click to propagate to the document itself, you need to take actions on the button click handler(like stopPropagation etc.)

Upvotes: 20

Mukesh Ram
Mukesh Ram

Reputation: 6328

$(document).on('click','.btn-edit',function()

This binds a click event to the document and all child elements within it. This method is referred to as delegated event handling.

$('#table-user').on('click','.btn-edit',function()

binds the click event to the #table-user directly. captures the event directly on the element.

Upvotes: 28

Related Questions