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

<script language=”javascript” type=”text/javascript” src=”jquery.js”></script>

I am goining to use following HTML code to explain how can we attach an event to the element.

<div>
<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

$(document).ready(function(){
$(“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>

Advertisement

3 Responses to “JQuery Event”

  1. Pawandeep Singh Says:

    Hey thanks man.. its really helpfull…

  2. Manoj Says:

    Excellent!!!

  3. Yogesh Says:

    Hey Thanks for simple and nice article,
    You are Genius…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.