-1

Which of the following ways is more efficient? What is the difference?

A

  $("body").on('click', '.picker', function(){ alert("A");});

B

  $('.picker').on('click', function(){ alert("B");});
user3260177
  • 113
  • 2
  • 7
  • 1
    Have you tried profiling this, either in your browser's dev tools or on a site like jsperf? – Ben Jacobs Apr 10 '14 at 16:52
  • 1
    They're not comparable, so their 'efficiency' is irrelevant. – David Thomas Apr 10 '14 at 16:55
  • You're comparing the selectors (DOM selection)? Or the efficiency of the event handling? I can't tell what you're asking. Like @DavidThomas suggested, your two lines of code are doing two different things. – cookie monster Apr 10 '14 at 16:56
  • As to the difference: [Difference between jQuery `click`, `bind`, `live`, `delegate`, `trigger` and `on` functions](http://stackoverflow.com/questions/2954932/difference-between-jquery-click-bind-live-delegate-trigger-and-on) – cookie monster Apr 10 '14 at 17:04
  • If there are many `.picker` elements or if they're created dynamically it would make sense to use B, otherwise I'd use A. – Ja͢ck Apr 10 '14 at 17:07

1 Answers1

0

Depends on the situation.

A advantages

  • .picker could be more than just a few. Delegating the handler to a parent, and not attaching a handler to each .picker reduces overhead.
  • If .picker is an element that is loaded dynamically, but you need to set handlers ahead of time.

B advantages

  • The handler is directly on the element. The event does not need to bubble up the DOM to trigger handlers.

In a similar context, .live was deprecated because handlers were placed on document, the highest node in the DOM tree. It caused latency.

Joseph
  • 117,725
  • 30
  • 181
  • 234