How to force the dialog box to close when clicking on any place outside the window?

$('.dial').dialog({ autoOpen:false; //Изначально закрыто }); $('img').click(function(){ $('.dial').dialog("open"); //По щелчку по картинки открывается }); $(document).click(function(){ $('.dial').dialog('close'); //По щелчку на любом месте закрывается }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <div title="Окно" class="dial"> 132 </div> 

    2 answers 2

    3 problems:

    • inside the object should not be ;
    • after the opening of the dialogue the event pops up to the document - it makes sense to cancel it
    • it makes sense not to close the dialog when clicking inside it

     $('.dial').dialog({ autoOpen: false }); $('img').click(function (event){ $('.dial').dialog("open"); event.stopPropagation(); }); $(document).click(function (event) { if (!$(event.target).closest(".dial").length) { $('.dial').dialog('close'); } }); 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <img src="//i.stack.imgur.com/huPUd.jpg?s=128&g=1" /> <div title="Окно" class="dial">132</div> 

       $('.dial').dialog({ autoOpen:false; //Изначально закрыто. }); $('img').click(function(){ $('.dial').dialog("open"); //По щелчку по картинки открывается }); $(document).click(function(event){ if($(event.target).closest("img, .dial").length) return; $('.dial').dialog('close'); }); 
      • one
        The golden rule, before writing on stackoverflow, is better to google. Can you mark your answer with an answer?) - DimenSi
      • Anything in this code syntax error? - Qwertiy
      • You are the pro; in the facility? - DimenSi
      • @DimenSi, yes, about ; . - Qwertiy