Reputation: 2791
I have declared two div one after other in layer format, which means "DIV2 (#myDiv2) will be placed over the DIV1 (#myDiv1). For single click on DIV2, it has to be hide. It works fine. But when I double click the DIV2, DIV2 gets hide by the first click of that double click event and then double click event also binding to the DIV1. I don't know how it happens. My requirement is when I double click the DIV2, DIV2 has to hide and then single click event only needs to bind for the DIV1.
$("#myDiv2").click(function(e) {
$(this).css("display", "none");
});
$("#myDiv1").dblclick(function(e) {
alert("DIV 1 double clicked");
});
<div id="myDiv1" style="height:100px;width:100px;background-color:red;"></div>
<br/>
<div id="myDiv2" style="background-color:green; width:100px;margin-top:-80px;height:40px">I am Div 2</div>
Upvotes: 2
Views: 261
Reputation: 1618
The dblclick
event queues the click
event and check for the target element. The visibility hidden interferes and the second immediate click is fired on target element.
One solution is to, unbind and bind the dblclick
event with a timeout after hiding the second div
.
$("#myDiv1").on('dblclick', runOnDoubleClick);
$("#myDiv2").on('click', function(e) {
$(this).hide();
$("#myDiv1").off('dblclick');
setTimeout(function() {
$("#myDiv1").on('dblclick', runOnDoubleClick)
}, 300);
});
function runOnDoubleClick()
{
alert("DIV 1 double clicked");
$("#myDiv2").show();
}
Upvotes: 2
Reputation: 1829
I think you got the click events confused, try this:
$("#myDiv2").dblclick(function(e) {
$(this).css("display", "none");
});
$("#myDiv1").click(function(e) {
alert("DIV 1 double clicked");
});
Upvotes: 0