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

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) 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 is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: