Search code examples
javascripteventsjquery-eventsjsfiddle

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


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!


Solution

  • Update the mousedown event like below :

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