What is the difference when I use $(document).on("click","#btn-id", function(){ }); and other hand is $("#btn-id").click() in JavaScript?
home / developersection / forums / difference between $(document).on() and $("#btn-id").click() function in javascript?
What is the difference when I use $(document).on("click","#btn-id", function(){ }); and other hand is $("#btn-id").click() in JavaScript?
Aryan Kumar
16-Aug-2023The main difference between
<span class="math-inline">\(document\)\.on\(\)\and `("#btn-id").click()is that(document).on()‘isadelegatedeventhandler,while‘("#btn-id").click()` is a direct event handler.A delegated event handler is attached to the document, and it listens for events on all child elements. When an event occurs on a child element, the delegated event handler is called, and it can then determine which child element the event occurred on. This can be useful for events that you want to listen for on multiple elements, such as clicks or hovers.
A direct event handler is attached to a specific element, and it is only called when an event occurs on that element. This can be useful for events that you only want to listen for on a specific element, such as a button click.
In the following example, the
<span class="math-inline">\(document\)\.on\(\)\function is used to attach a click event handler to all buttons on the page. The `("#btn-id").click()function is used to attach a click event handler to the button with the idbtn-id`.JavaScript
In general, you should use delegated event handlers whenever possible. This is because delegated event handlers are more efficient, as they only need to be called once for each event, regardless of how many child elements are involved.
However, there are some cases where you may need to use a direct event handler. For example, if you need to listen for an event on a specific element, or if you need to prevent the default behavior of an event.