Matt Parkins
Matt Parkins

Reputation: 24708

Is there a shorter way of writing $(document) in jQuery?

Is there a shorter way of writing $(document) in jQuery. I'm replacing all my

$("#id").live(...) 

function calls for

$(document).on("touchstart click" ...) 

and want to save valuable keypresses.

Upvotes: 0

Views: 73

Answers (1)

Anthony Grist
Anthony Grist

Reputation: 38345

You could cache it in a variable:

var $d = $(document);

then simply use $d in place of it elsewhere in your code. So:

$d.on('events', 'selector', function() {...});

However, when using .on() you should ideally bind the event handlers on static elements closer to the dynamic elements than the document, so it doesn't have to travel so far up the DOM tree before being handled.

Upvotes: 4

Related Questions