Tuesday, May 22, 2012

JQuery Basics - Part II



JQuery Events

Jquery events have several methods which are used to execute a set of instructions when the user interacts with the web pages. We have Keyboard events (keypress, keyup, keydown), Mouse events (click, hover, double click,...) and Form events (submit, focus, blur,...). Event handlers are set of instructions will execute whenever state change occurs.

Usage

$('selector').events(function() {
// code...
});

Examples
1.  <div id='myid1'>Click me!</div>

$('#myid1').click(function() {
$('#'+this.id).html('Clicked');
});
 
2.  <input type='text' id='txt1' value='Enter value' > </input>

$('#txt1').focus(function() {
$(this).val('');
})
.keypress(function(event) {
if(event.which == '13')
alert('enter pressed');
})
.blur(function() {
alert($(this).val());
});

We can also apply event handlers using class attribute or by specifying the elements directly. For example

$('a').click(function(e) {
alert(this.id); });
});
will apply the routine to all anchor tag in the web page.

Apart from the above events, we also have methods like:
on(), off() to attach and de-attach event handlers from the elements
bind() to bind the event handlers
live() to attach event handlers to elements (both static and dynamic)


JQuery Ajax

No comments:

Post a Comment