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?
$( document ). ready()A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ). ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.
Basically, both are the same. But when this keyword is used inside $(), then it becomes a jQuery object, and now we can use all properties of jQuery on this method. Example: HTML.
So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.
$(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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With