Double click snaps to parent or child when I double click on a specific element to hide with one click

I have declared two divs one after the other in a layer format, which means that "DIV2 (# myDiv2) will be placed above DIV1 (# myDiv1). For a single click on DIV2 it must be hidden. But when I double click on DIV2, DIV2 gets hidden first click on this double click event and then double click on the event also bound to DIV1. I don’t know how this happens. My requirement is when I double click on DIV2 the DIV2 should hide and then one click event only needs to be bound for 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>
      

Run code


+3


source to share


2 answers


The event dblclick

stops the event click

and checks the target element. Hidden visibility gets in the way and the second click instantly fires on the target element.

One solution is to disable and bind the dblclick

timeout event after hiding the second one div

.



JSFiddle

$("#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();
}

      

+2


source


I think you have lost the click events, try this:



$("#myDiv2").dblclick(function(e) {
  $(this).css("display", "none");
});
$("#myDiv1").click(function(e) {
  alert("DIV 1 double clicked");
});

      

0


source







All Articles