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

No comments:

Post a Comment