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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: