0

I make a JavaScript driven html popup box . The code work perfectly for me ,but now I need to press the close link to close the popup box. How can I modify the below code so that I can also close the popup box by clicking outside the popup box.

function toggle_visibility(id) {
  var e = document.getElementById(id);
  if (e.style.display == 'block')
    e.style.display = 'none';
  else
    e.style.display = 'block';
}
#popupBoxOnePosition {
  top: 0;
  left: 0;
  position: fixed;
  width: 100%;
  height: 120%;
  background-color: rgba(0, 0, 0, 0.7);
  display: none;
}
.popupBoxWrapper {
  width: 550px;
  margin: 50px auto;
  text-align: left;
}
.popupBoxContent {
  background-color: #FFF;
  padding: 15px;
}
<div id="popupBoxOnePosition">
  <div class="popupBoxWrapper">
    <div class="popupBoxContent">
      <h3>Popup Box 1</h3>
      <p>You are currently viewing popup box 1.</p>
      <p>Click <a href="javascript:void(0)" onclick="toggle_visibility('popupBoxOnePosition');">here</a> to close popup box one.</p>
    </div>
  </div>
</div>

<p>Click <a href="javascript:void(0)" onclick="toggle_visibility('popupBoxOnePosition');">here</a> to see popup box one.</p>

Please note I try below code but it doesn't work for me

 $('#popupBoxOnePosition').click(function(event){
                         event.stopPropagation();
 });
Geordy James
  • 2,358
  • 3
  • 25
  • 34
  • 1
    Bind an event to the `window` to close the popup onclick and then use `event.stopPropagation()` when clicking on the popup itself http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element – Yoav Kadosh Jun 24 '16 at 02:40
  • @YoavKadosh That code doesn't work for me that is why I ask this question – Geordy James Jun 24 '16 at 04:08
  • @Barmar That code doesn't work for me that is why I ask this question .Then how can it be a duplicate question. – Geordy James Jun 24 '16 at 04:19
  • Please show what you've tried. You show the code that stops propagation when clicking in the box, but where it the code that closes the box when you click somewhere else? – Barmar Jun 24 '16 at 04:21
  • @GeordyJames your code is missing `$(window).click(function(){ /* Hide popup */ });` – Yoav Kadosh Jun 24 '16 at 04:34
  • @YoavKadosh I also try that but it cause my popup div tag to close automatically just by displaying it for blink of a sec. $(window).click(function(){ $("#popupBoxOnePosition").fadeOut(); }); – Geordy James Jun 24 '16 at 04:54
  • 1
    In your case, since the popup box has a background that is covering the entire window, you have to bind the event to the popupbox wrapper rather than to the window. Here is a fiddle https://jsfiddle.net/hfh8u00k/1/ – Yoav Kadosh Jun 24 '16 at 05:32

0 Answers0