JQuery Event
November 2, 2009
This is a basic article which will help you, how to attach an events to the elements at runtime so that you can make a clean html code.
To work with this code you basically need a JQuery library which you will get from http://jquery.com/
First include the jquery.js file in your .htm file as follows
I am goining to use following HTML code to explain how can we attach an event to the element.
<h2 class=”row”>
<a href=”#”>Tab 1</a>
</h2>
<h2 class=”row”>
<a href=”#”>Tab 2</a>
</h2>
<h2 class=”row”>
<a href=”#”>Tab 3</a>
</h2>
</div>
Now following JQuery code will attach an events to <a> tag
$(“h2.row > a “).click(function () {
var innerHTML = $(this).html();
alert(innerHTML) ;
// or write your own code
});
});
In the above code $(document).ready(function(){ }); is similar to window.onload = function ( ) { } with a small difference that the $(document).ready(function(){ }); waits for document to load.
Once it is loaded then it will find the all
<h2><a href=”#”>bla bla bla</a></h2> combination using $(“h2.row > a “); the meaning of this statement is find all <a> tag which are under <h2> tag having class “row”
After finding such a element it will attach click event to it using $(“h2.row > a “).click(function( ) { // place your code here });
So by this way you can attach events to the elements without writing
<a href=”#” onClick=”showText(this)”>bla bla bla</a>