The first part of your question has been adequately answered by other answers. You were calling your console.log()
function rather than passing a reference to a function that can be called later.
To answer the second part of your question which nobody else has yet addressed:
Yes, it will perform better to scope your event handler to a closer ancestor of the button rather than use $('body')
.
You should pick an ancestor of your buttons that is as close to the buttons as possible, but is statically present at the time you install your event handler (and not dynamically destroyed/created later).
One main reason that .live()
was deprecated in favor of .on()
is that .live()
put all it's event handlers on the document
object and in a busy page, there can be a LOT of delegated event handlers on the document
object. When that occurs, ever single event bubbles all the way up to the document
object and then every single event has to be compared to a long list of possible delegated event handlers. Since this usually means running a selector operation vs. the eventTarget
, this can really get slow.
If, on the other hand, you select an ancestor object that is much closer to the desired eventTarget, then a much smaller list of events from a much smaller list of objects flows through this particular delegated event handler and the whole event system can perform better.
For best performance with lots of events/objects, delegated event handlers should be applied as close to the target objects as possible.