Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery on does not work but live does using 1.7.1 library

Tags:

jquery

events

i have a button that is created dynamically so i need to use .live on my code. Here's an example:

$('#send').live('click', function(){
.....
..... code .....
.....
});

I'm using jQuery library 1.7.1 and i wanted to change it to using .on but it does not work. Why is this? Is the syntax different?

I looked at the documentation and I dont seem to be doing anything wrong. I dont mind leaving it like live but i would like to know if I'm doing something wrong.

http://api.jquery.com/on/

like image 280
Samuel Lopez Avatar asked Dec 28 '11 00:12

Samuel Lopez


2 Answers

Is the syntax different? Yes. Did you read all of the .on() doco page you linked to?

The following summary about how to switch from .live() to .delegate() or .on() is from the .live() doco page:

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

So in your case you want:

$(document).on('click', '#send', function(){
   // your code here
});

Note though that ideally you won't be using $(document), you'll be using $(someotherelement) to attach the handler to an element closer to your '#send' element. If you can, use whatever the direct parent element of '#send' is, or if the parent is dynamically created too use its parent.

like image 53
nnnnnn Avatar answered Nov 15 '22 21:11

nnnnnn


To use event delegation, .on requires two selectors, like .delegate.

$('some container').on('click', '#send', function() { ... });
like image 24
SLaks Avatar answered Nov 15 '22 20:11

SLaks