Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add jQuery event to all current and future elements?

I just noticed that live() is already deprecated in jQuery. I have quick question (just to make sure which method is the most efficient, the fastest and up-to-date). I've got myfunction() and I want to bind() it to all current and future elements with attr("title") == 'x'.

Is this what I should use:

jQuery("???").bind("mouseup", myfunction);
jQuery("???").bind("keyup", myfunction);

Or this:

jQuery("???").delegate("???", "mouseup", myfunction);
jQuery("???").delegate("???", "keyup", myfunction);

Or this:

jQuery("???").on("mouseup", "???", myfunction);
jQuery("???").on("keyup", "???", myfunction);

I'm also having problem specifying correct selector(s) - because some of them allow to attach event to one thing (like body or document) and they allow second selector.

like image 276
Atadj Avatar asked Aug 26 '12 20:08

Atadj


2 Answers

Use .on() instead, with an attribute equals selector:

$(document).on('mouseup', '[title="x"]', myfunction);
like image 144
João Silva Avatar answered Nov 08 '22 07:11

João Silva


The syntax that replaces .live() is like this:

$('#parent').on('keyup mouseup', '.children', myfunction);
like image 33
Blender Avatar answered Nov 08 '22 07:11

Blender