With jQuery 1.4.2 launch, a new method called "delegate()" was
introduced. This method attaches a handler to one or more events for
selected/specified elements. Let's take an example. I have created a
table and using delegate method, I will attach the click event handler
to every td element.
jQuery delegate() method code.
It takes 3 arguments.
1. Selector
2. Event Type
3. Event Handler
See live Demo and Code.
You will say that this is very much possible with the bind() method. Below code will serve the purpose.
Then what's new with delegate() method?
bind() vs delegate()
bind() method will add event to element which are on the page when it was called. For example, there are only 4 td on the page when bind() was called. Later on, when you dynamically add more td in the table then bind() will not attach click event handler to those td. Let's extend our demo and place a button on the page which will add the td dynamically.
Now, when you run this page, you will not find click event for newly added td.
See live Demo and Code.
But with delegate(), you will find click event for newly added td. delegate() method adds event which are on the page and also listens for new element and add event to them.
See live Demo and Code.
01 | <table border= "1" width= "200px" cellspacing= "5" cellpadding= "5" > |
02 | <tr> |
03 | <td>Item 1</td> |
04 | <td>Item 2</td> |
05 | </tr> |
06 | <tr> |
07 | <td>Item 3</td> |
08 | <td>Item 4</td> |
09 | </tr> |
10 | </table> |
1 | <script src= "Scripts/jquery-1.4.2.min.js" type= "text/javascript" ></script> |
2 | <script type= "text/javascript" language= "javascript" > |
3 | $(document).ready( function (){ |
4 | $( "table" ).delegate( "td" , "click" , function (){ |
5 | alert( 'I am' + $( this ).text()); |
6 | }); |
7 | }); |
8 | </script> |
1. Selector
2. Event Type
3. Event Handler
See live Demo and Code.
You will say that this is very much possible with the bind() method. Below code will serve the purpose.
1 | $(document).ready( function (){ |
2 | $( "table td" ).bind( "click" , function (){ |
3 | alert( 'I am' + $( this ).text()); |
4 | }); |
5 | }); |
bind() vs delegate()
bind() method will add event to element which are on the page when it was called. For example, there are only 4 td on the page when bind() was called. Later on, when you dynamically add more td in the table then bind() will not attach click event handler to those td. Let's extend our demo and place a button on the page which will add the td dynamically.
1 | <input type= "button" value= "Add TD" id= "btnAdd" /> |
1 | $( "#btnAdd" ).click( function (){ |
2 | $( "table" ).append( "<tr><td>Item 5</td><td>Item 6</td></tr>" ); |
3 | }); |
See live Demo and Code.
But with delegate(), you will find click event for newly added td. delegate() method adds event which are on the page and also listens for new element and add event to them.
See live Demo and Code.
No comments:
Post a Comment