Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add event handler to an element that not yet exists using on()?

Tags:

I want to add an event handle to an element that will be created later in DOM.

Basically, what I am trying to do is that, when I click p#one, new element p#two will be created, then I click p#two, tell me "p#two" clicked. However, it doesn't work, I didn't get the console.log result of 'p#two clicked' after I click p#two.

I use on() to add click event to p#two. What do I do wrong?

Thanks.

Below is my example code:

<!DOCTYPE html> <html> <head>   <meta charset="utf-8">   <title>on() test</title>   <link type="text/css" href="http://localhost/jquery-ui-1.8.20.custom/css/smoothness/jquery-ui-1.8.20.custom.css" rel="stylesheet" />   <script type="text/javascript" src="http://localhost/jquery-ui-1.8.20.custom/js/jquery-1.7.2.min.js"></script>   <script type="text/javascript" src="http://localhost/jquery-ui-1.8.20.custom/js/jquery-ui-1.8.20.custom.min.js"></script>    <script type="text/javascript">     $(document).ready(function() {          $('p#two').on('click', function() {             console.log('p#two clicked');         });           $('p#one').click(function() {             console.log('p#one clicked');             $('<p id="two">two</p>').insertAfter('p#one');         });      }); // end doc ready   </script> </head>  <body>     <p id="one">one</p> </body> </html> 
like image 577
gilzero Avatar asked May 30 '12 17:05

gilzero


People also ask

Which method attaches an event handler to an element without overwriting existing event handlers?

The addEventListener() method attaches an event handler to an element without overwriting existing event handlers. You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events.

What does the ready () event handler run?

The . ready() method offers a way to run JavaScript code as soon as the page's Document Object Model (DOM) becomes safe to manipulate. This will often be a good time to perform tasks that are needed before the user views or interacts with the page, for example to add event handlers and initialize plugins.

Can you add an EventListener to a function?

The method addEventListener() works by adding a function, or an object that implements EventListener , to the list of event listeners for the specified event type on the EventTarget on which it's called.


2 Answers

$('body').on('click','p#two', function() {     console.log('p#two clicked'); }); 

you can also use

$(document).on('click', 'p#two', function() {  }); 

Read more about .on()

you can also use .delegate()

$('body').delegate('#two', 'click', function() {  }); 
like image 172
thecodeparadox Avatar answered Oct 13 '22 23:10

thecodeparadox


You can bind the $.on to a parent element that will always exist in dom like this.

$(document).on('click','p#two', function() {             console.log('p#two clicked');         }); 

Note that: you can replace document with any parent of the element that will always exist in dom, and the closer the parent the better.

Check doc of $.on

Live is depreciated. use $.on instead. Equivalent syntax of $.on for $.live and $.delegate

$(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+ 

I would suggest you to use $.on for all event handling purposes as all other methods routes through $.on method under the hood.

Check the definition of these functions from jQuery source v.1.7.2

bind: function( types, data, fn ) {     return this.on( types, null, data, fn ); }, unbind: function( types, fn ) {     return this.off( types, null, fn ); },  live: function( types, data, fn ) {     jQuery( this.context ).on( types, this.selector, data, fn );     return this; }, die: function( types, fn ) {     jQuery( this.context ).off( types, this.selector || "**", fn );     return this; },  delegate: function( selector, types, data, fn ) {     return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) {     // ( namespace ) or ( selector, types [, fn] )     return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); }  

You can see all methods are using $.on and $.off themselves. So using $.on you can at least save a function call though which isn't that significant most of the cases.

like image 32
Prasenjit Kumar Nag Avatar answered Oct 13 '22 21:10

Prasenjit Kumar Nag