0

Is it better to attach the on() event to the document or a closer parent?

Note: Initially this question had another aspect and a different topic. It became obsolete really quickly (typo in the source code)

1
  • 1
    Could you post the rest of your code, something else is happening to the <ul/> see here for an example of your code working jsfiddle.net/markcoleman/a6vzc Commented Jul 19, 2012 at 11:40

2 Answers 2

2

The best key for performance using jQuery is to use an id as the initial identifier. For example:

$('#my_id').on('click', 'tag.my_class', function () {
    ...
});

This allows jQuery to go straight to the container, and then begin trawling from there.

Sign up to request clarification or add additional context in comments.

Comments

1

if you bind the "on" event to the closest parent will produce exactly what are you looking for, click function will works fine even if it is appended to document, but in future if you append any elements with class "clickable" will also get binded. so its always good practice to append the "on" event to closest parent rather than whole document.

if you want more specific you can use

$("ul.media-grid").on('click', 'li.clickable', function () {
  alert("works")
});

as it will get the ul with the class "media-grid" and appends the event to the li's with class "clickable"

4 Comments

is it only good practice or will it improve performance, too?
@Horen it will also increase the performance mate, because instead of looking whole document and find the li's with the class "clickable", it will look for the ul with the class "media-grid" and do so.
@Nick sure mate, using id's instead of classes is good practice, because, if you want to perform similar functionality for one or more elements we can use classes, when you need some functionality to be added to one particular element, its good to use id's.
@shreedhar I mostly agree with you, but I'm confused by the jquery docs about .live(). There it states that one of the downsides of .live() is that "jQuery attempts to retrieve the elements specified by the selector before calling the .live() method, which may be time-consuming on large documents." That implies that .on() doesn't do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.