Why is the mousedown event getting rid of my click event?

221 Views Asked by At

I am having an issue where my click event in a specific case is not being called. I can explain better using this example in the fiddle. I have also pasted the code below.

https://jsfiddle.net/qtdvn8oc/3/

<html>
    <input type="button" id="openId" value="Open" />
    <div id="qbr"></div>
</html>
$(document ).on("mousedown",function() {
  console.log("mousedown");
  $('#qbr').hide();
});

$("#openId").on("click", function() {
  console.log("open");
  $('#qbr').html("BLAH BLAH <input type=\"button\" id=\"closeId\" value=\"Close\" />");
  $('#qbr').show();
});

$(document).on('click', "#closeId", function(e){
  e.stopPropagation();
  console.log("close");
  $('#qbr').hide();
});

Look at the fiddle's console to see the issue I am facing. When you click on the open button, you see the text and the close button. And it prints "mousedown" and "open" in the console. Now when you click on the close button, you only see "mousedown" in the console. I need it to hit both mousedown and the close click events. This has to do with hiding the div on mousedown, but I do need that in place. (The mousedown is there to close the div when you click anywhere on the document, think how a menu works).

Any help will be appreciated!

Thank you!

2

There are 2 best solutions below

1
Vignesh Pandi On BEST ANSWER

Update the mousedown event like below :

$(document ).on("mousedown",function(e) {
  if(e.target.id === 'closeId'){
  return;
  }
  console.log("mousedown");
  $('#qbr').hide();
});
0
alph On

For my solution, I see that the mousedown event listener was added to the entire document, including the #qbr div. In order for your code to work, you have to select the entire document excluding #qbr like so: $("*:not(#qbr)")

Then, for each element selected, we have to exclude the listener for child elements using this: if (event.target !== event.currentTarget) return This is to make sure clicking on #qbr does not trigger the listener for <body>, or any other parent listener.

With this two changes the code will look something like this.

$("*:not(#qbr)").on("mousedown",function(event) {
  if (event.target !== event.currentTarget) return;
  event.stopPropagation();
  console.log("mousedown");
  $('#qbr').hide();
});

$("#openId").on("click", function() {
  console.log("open");
  $('#qbr').html("BLAH BLAH <input type=\"button\" id=\"closeId\" value=\"Close\" />");
  $('#qbr').show();
})
$(document).on('click', "#closeId", function(){
  console.log("close");
  $('#qbr').hide();
});