Event Handling of Control in JQuery


This article is to demonstrates how we can attach events to any HTML/ASPX controls and then trigger them. There are various ways by which we can trigger the events. This article is useful for the JQuery starters to understand how event handling works in JQuery. Learn Event Handling of Control in JQuery

Event Handling with JQuery


JQuey is extremly useful with attaching events to HTML/ASPX controls. It's easy to attach and can be executed programmatically or on user's interaction.

The .click() Event Handler



The click event is very common and often used everywhere. In JQuery, we can attach the click event to any control. The click event has following possible implementations:

.click(handler(eventObject))
.click(eventData, handler(eventObject))

Example



<div id="myDiv1">
</div>

<div id="myDiv2">
</div>



To attach click event to above DIVs, we can write the following code in script:


$('#myDiv1').click
(
function()
{
alert('This event is triggered using JQuery for myDiv1');
}
)



We can also trigger event programmtically in any other event handler or in any other place in script. See the example below:


$('#myDiv2').click
(
function()
{
$('#myDiv1').click(); //will execute myDiv1.click event
}
)




There is another way to trigger event programmtically:


var div1 = $('#myDiv1');
div1.trigger('click');


In above example, you can trigger any event associated with the control.

quite nice isn't it?



One Event Handler for Multiple Controls



JQuery offers another good feature to define one single event for multiple controls, the only condition is that all the controls must be of same type or same tag. Example below shows how we can attach event to multiple <p> tags:


<p>First p tag is defined here</p>
<p>This is second p tag</p>
<p>Third p tag is defined and this is last</p>

$('p').click
(
function()
{
$(this).slideUp();
}
)


$(this) denotes the object for which the event is triggerd.


Comments

Author: Alwyn Duraisingh30 Nov 2011 Member Level: Gold   Points : 0

What are all the relative js file i should need to get the code run. Please add the link also while posting the JQuery resources.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: