www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons jQuery Dynamic Event Handling using on() Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Lesson 24
Lesson 25
Lesson 26
Lesson 27
In the previous lessons, we used the on() method to subscribe to events and we used the off() method to unsubscribe the events. Our on() and off() friends worked great for existing elements.

What about the elements that we later add to our page dynamically or programmatically.

Well, one solution would be to handle them manually, manipulating the HTML of the element(s) that we add dynamically. This works fine, but jQuery offers an elegant way to do so.

We can use and overload of the on() method to do the dynamic event handling. The following example illustrates this:

<input id="addLink" type="button" onClick="addLink();" value="Add New Link">
<br>
<div id="addLink"></div>
<br>
<a href = "javascript:void(0);"> Test On() </a>
<br>
<script type = "text/javascript" >

$ ( function ()
{
$ (document). on ( "click" ,"a", function () {
alert ( $ ( this ). text ());
});
});

function addLink() {
$("#addLink").after("<br><a href = 'javascript:void(0);'> Added Link </a> ");
}
</script>

In the above example the on() method is called selecting the document object. The on() method here takes three parameters i.e. the event, the selector followed by the anonymous function.

When we run the above code and click on the "Test On()" link, it pops up an alert box displaying the text of the link. Clicking on the "Add New Link" adds a new <a> element to the page, dynamically. Clicking on this dynamically added link also fires the same event handler function.
Next >>> Lesson No. 25: jQuery Ajax





Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.