Saravana
Saravana

Reputation: 531

Jquery code performance on '.on' method

Does the following code make any impact on application's performance?

$("body").on('click','#id',function () {
   //code to be executed
});

if so, could any one please explain why?

Upvotes: 0

Views: 40

Answers (1)

Amadan
Amadan

Reputation: 198324

Yes, but slight. The reason is that it would capture every click on the document's body, then evaluate whether that bubbled up from #id, and exit if it is not. It is a good policy to attach the handler to the most tightly defined element that will contain all of your events, as you rarely need to go as wide as body - for example, $("#stuffgoeshere").on('click','#id',function...). And if you actually know the ID of the element and that element exists, it would be even better to attach the handler directly to the element, using $('#id').on('click', function...).

Upvotes: 2

Related Questions