good_evening
good_evening

Reputation: 21749

Selecting the whole body to the on()

$('body').on("click", "ul.typeFirst li a.username", function(e)

Is it okay to do it? The reason why I do this is because ul like the above can be loaded dynamically many times. I am just wondering if it's okay selecting the whole body or it's much better to create a div or something and select that div and to load elements dynamically into that div.

Upvotes: 1

Views: 65

Answers (2)

dsgriffin
dsgriffin

Reputation: 68586

Yes, it's fine to do so (although I believe using $(document) is actually faster than using $('body')).

However, if all the elements in question were to be contained in the same container <div>, selecting it via. that <div> would be the preferred and most efficient solution.

Basically, whenever you are able to localise (and by localise I mean focus on) a particular section of elements relevant to your event(s), you should do so.

Upvotes: 3

bryjohns
bryjohns

Reputation: 656

It is important to know what is actually going on. Take a look at this site to see how events traverse through the dom. http://www.quirksmode.org/js/events_order.html

You are doing something called delegating. It is much more expensive than binding the event to the element you actually want because it has to do a check on the event target on every click. Its probably fine for what you're using it for but you want to be careful with it. You wouldn't want to do it on the body level for things like mouseover events.

Upvotes: 1

Related Questions