July 25, 2009

Detect any Event on an Element using jQuery




The jQuery event.type is very useful when you want to detect the nature of an event on an Element and determine if it was a click, doubleclick, mousemove, mouseenter and so on. Here’s how to detect the Event Type on an Element with minimal code in jQuery

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Detect any event</title>

<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$('.someDiv').bind('click dblclick mousedown mouseenter mouseleave',
detectEvent);

function detectEvent(e) {
$('.para').text('Current Event is: ' + e.type);
}
});
</script>
<
style type="text/css">
.someDiv
{
height:400px;
width:400px;
background-color:Gray;
}
.para
{
background-color:Black;
color:White;
}
</style>
</
head>
<
body>
<
div>
<
div class="someDiv"/>
<
p class="para" />
</
div>

</
body>
</
html>

Live Demo

To test the functionality, run the piece of code shown above and perform a click, doubleclick, mousemove, mouseenter and so on on the Gray area



Giving me +1 tells me you liked this article! Thanks in advance


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Detect any Event on an Element using jQuery"
 

Copyright © 2009-2013 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions