jQuery: Detect Double Click in a Div

Here’s a very simple piece of code that shows how to detect double click in a DIV element. In order to detect a single click, double click and other mouse events, jQuery has a set of Mouse events that you can use.

In this example, we will toggle the border color and size of a DIV when it is double clicked

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Detect Double Click (from DevCurry.com)</title>
<style type="text/css">
div{
border: 1px solid black;
height:100px; width:200px;          
}
.alt
{
border: 4px solid red;          
}
</style>
<script type="text/javascript"
src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.2.min.js">
</script>

<script type="text/javascript">
$(function () {
$('#divOne').dblclick(function () {
$(this).toggleClass('alt');
});
});
</script>
</head>
<body>
<div id="divOne">
</div>

</body>
</html>

As you can see, we are using toggleClass to toggle the CSS class of the DIV whenever the user double clicks it. To detect a double click, we are using the in-built jQuery mouse event .dblclick(). Similarly you can attach this event to any HTML element.

See a Live Demo




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: