0

I'm facing a problem with dialog closing in JQuery

Here's the code I have :

    $(window).on("click",function(e){
        if($(e.target).not("#test")){
            $("#test").hide();
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dialog open id="test"></dialog>
<input type="submit" onclick="$('#test').show()">

Well, function works like it supposed to(closes dialog when I click outside of it's content) but then I can't toggle it again. Because of the function, I suppose.

Also I tried to fix it with such way but it don't work either :

if($("#test").css("display","block")){
    $(window).on("click",function(e){
        if($(e.target).not("#test")){
            $("#test").hide();
        }
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dialog open id="test"></dialog>
<input type="submit" onclick="$('#test').show()">

Is there any way to fix this?

That you very much for spending your precious time with my problem!

Thank you very much for any help or advice!

2 Answers2

1

Your submit click event fires first and then the window click event fires. Hence your dialog keeps getting hidden. Ensure you are not propagating the click event from your submit button if you want to show the dialog.

You might want to add validation to ensure your dialog is not already open when clicking submit though.

$(window).on("click", function(e) {
  console.log('window click');
  if ($(e.target).not("#test")) {
    $("#test").hide();
  }
});

$('input[type=submit]').on('click', function(){
  $('#test').show();
  event.stopPropagation();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dialog open id="test"></dialog>
<input type="submit" onclick="">
Nope
  • 22,147
  • 7
  • 47
  • 72
0

You don't need show or hide functions, you just need to use the open property and change it to false or true.

    $(window).on("click",function(e){
        if($(e.target).not("#test") && !$(e.target).is("#submit")){
            $("#test")[0].open = false; // or document.getElementById("test").open = false;
        }
    });

    $('#submit').click(function() {
       $('#test')[0].open = true; // // or document.getElementById("test").open = true;
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dialog open id="test"></dialog>
<input type="submit" id="submit">
Claudio
  • 5,078
  • 1
  • 22
  • 33
  • This isn't supported in internet explorer, Edge or Firefox. Links to official documentation and MDN instead of that w3schools... W3: https://www.w3.org/TR/html53/interactive-elements.html#the-dialog-element and MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog#Examples – Nope Jan 05 '18 at 12:56