2

The scenario is as follows.

enter image description here

  1. Default Status (no layer popup)
  2. When I click the button, layer popup shows.
  3. Click the button or outside, layer popup will be hide.

I want to close the layer popup when I click background(outside) or button.

How can I do with Vanilla JS or jquery? (based on HTML)

I would appreciate it if you could answer.

Pawara Siriwardhane
  • 1,873
  • 10
  • 26
  • 38
jwisdom
  • 21
  • 2
  • like this post? https://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it , or you can see thid fiddle http://jsfiddle.net/LCB5W/ – frankfurt Oct 27 '21 at 06:13

5 Answers5

1

When you open the popup attach a click listener to body that closes it and removes the listener.

ray
  • 26,557
  • 5
  • 28
  • 27
1

You can use this code

//use by id

document.getElementById(#id).style.display = 'block';
document.getElementById(#id).style.display = 'none';

//use by className 



document.getElementById(.className).style.display = 'none';
document.getElementById(.className).style.display = 'block';

or use jQuery

$(document).ready(function(){
       $("#id").click(function(event){
         // $("#id").toggle();
         // $("#id").hide();
         // $("#id").show();
       });
     });
0

Set id for your layer in HTML part like id="layerPopup" Then on your JS code create event for your button

$(document).on('click', '#btnId', function(){ 
    $("#layerPopup").hide();

});
Freedom Rider
  • 27
  • 1
  • 8
0

You should appear a overlay which will cover the whole body, and give it css property z-index to lower from the button, and when apply click function on it same as my code

HTML

<div class="overlay"></div>

CSS

.overlay{
   background-color: transparent;
   inset: 0;
   position: fixed;
   z-index: 100;
   display: none;
}

button{
 z-index: 101;
}

JQuery

$('button').click(function(){
    $('.overlay, popup').toggle();
});

$('.overlay').click(function(){
    $('.overlay, popup').hide();
});
Zain Ejaz
  • 289
  • 1
  • 9
0

One standard way to handle such scenario is to have a backdrop div behind the popup and then add an event listener to it. You may choose to change backdrop's background color to increase pop up aesthetics visibly.

.backdrop {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  z-index: 10;
  background: rgba(0, 0, 0, 0.75);
}

.modal {
  position: fixed;
  top: 30vh;
  left: 10%;
  width: 80%;
  z-index: 100;
  overflow: hidden;
}
<div class="backdrop" />
<div class="modal" />

And then you can add an event listener on backdrop:

$(document).on('click', '.backdrop', function(){ 
    $(".modal").hide();
});

PS: There may be some syntax issues!

Pavan J
  • 353
  • 1
  • 3
  • 12