Hiding a Dialog Box on Outside Click


/ Published in: jQuery
Save to your folder(s)

This is essentially how to detect an outside click for a dialog box on a website, using HTML/CSS/Javascript/JQuery.

Essentially you need to understand event propagation how it works throughout the DOM with JQuery, to make this as simple as possible. Add a listener to the html or body element that detects a click, hide the box when it receives that event. Otherwise, stop the propagation of the event when the container receives it (the event).

If you have any question, or want a further explanation, don't hesitate to get in contact with me.

Cheers!


Copy this code and paste it in your HTML
  1. <!DOCTYPE html>
  2. <html lang='en-us' xmlns='http://www.w3.org/1999/xhtml'>
  3. <head>
  4. <meta charset='utf-8'>
  5. <title>Page Title</title>
  6. <style type="text/css" media="screen">
  7. .button-container
  8. {
  9. width:300px;
  10. margin:0 auto;
  11. text-align: center;
  12. padding:0px 0px 25px 0px;
  13. }
  14. .form-container
  15. {
  16. display:none;
  17. width:300px;
  18. margin:0 auto;
  19. text-align: center;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <div class="button-container">
  25. <button>Show Form</button>
  26. </div>
  27. <div class="form-container">
  28. <form action="event_prop_submit" method="get" accept-charset="utf-8">
  29. <fieldset id="" class="">
  30. <legend>Personal Information</legend>
  31. <label for="first_name">First Name</label><br/>
  32. <input type="text" name="first_name" value="" id="first_name" />
  33. <br/><br/>
  34. <label for="last_name">last_name</label><br/>
  35. <input type="text" name="last_name" value="" id="last_name">
  36. <br/><br/>
  37. </fieldset>
  38. <p><input type="submit" value="Continue &rarr;"></p>
  39. </form>
  40. </div>
  41. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  42. <script type="text/javascript">
  43. $(document).ready(function(){
  44. $('.form-container').click(function(event){
  45. console.log('click - form');
  46. //we want all click events in the form to stop at the form-container element, so that the event does not reach the body element
  47. event.stopPropagation();
  48. });
  49. $('html').click(function(event){
  50. console.log('click - body');
  51. //hide the form if the body is clicked
  52. $('.form-container').css('display','none');
  53. });
  54. $('button').click(function(event){
  55. $('.form-container').css('display','block');
  56. event.stopPropagation();
  57. });
  58. });
  59. </script>
  60. </body>
  61. </html>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.