Close lightbox on click outside of the child div - javascript

I'm creating a lightbox without using a jquery plugin, and now I'm trying to close it by clicking on the close button or by clicking anywhere else outside of the white area (.white_content)
Jsfiddle Example
<button onclick="document.getElementById('lightbox').style.display='inline';">
Show lightbox
</button>
<!-- LIGHTBOX CODE BEGIN -->
<div id="lightbox" class="lightbox" style="display:none">
<div class="white_content">
Close
<p>Click anywhere to close the lightbox.</p>
<p>Use Javascript to insert anything here.</p>
</div>
</div>
<!-- LIGHTBOX CODE END -->
Although it's not just like I want it. I want it to close only if I click on the dark area of the lightbox and not on the white container (.white_content), I've heard that event.propagation can be a bad thing to use, so here's how I'm closing the lightbox
$(document).on('click', function(event) {
if (!$(event.target).closest('button').length) {
$(".lightbox").hide();
}
});

you can change you condition bit like below
$(document).on('click', function(event) {
if ($(event.target).has('.white_content').length) {
$(".lightbox").hide();
}
});

Most lightbox scripts are using two div-s, content and overlay. Overlay is there for background and to prevent users to click on page content, and also click on overlay can be used to close lightbox.
HTML:
<div id="lightbox"> LIGHTBOX CONTENT </div>
<div id="overlay"></div>
JS:
$( '#overlay, #close').on('click', function(event) {
$("#lightbox, #overlay").hide();
});
$( '#show').on('click', function(event) {
$("#lightbox, #overlay").show();
});
EXAMPLE

You want to close the lightbox on any click that isn't targeting the lightbox or one of its children. Your existing code is pretty close:
$(document).on('click', function(event) {
if (!$(event.target).closest('button').length &&
!$(event.target).closest('.white_content').length) {
$(".lightbox").hide();
}
});
$(document).on('click', function(event) {
if (!$(event.target).closest('button').length &&
!$(event.target).closest('.white_content').length) {
$(".lightbox").hide();
}
});
.textright {
float: right;
}
.lightbox {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
background:rgba(0, 0, 0, .8);
}
.white_content {
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 5px solid gray;
background-color: white;
z-index:1002;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="document.getElementById('lightbox').style.display='inline';">
Show lightbox
</button>
<!-- LIGHTBOX CODE BEGIN -->
<div id="lightbox" class="lightbox" style="display:none">
<div class="white_content">
Close
<p>Click anywhere to close the lightbox.</p>
<p>Use Javascript to insert anything here.</p>
</div>
</div>
<!-- LIGHTBOX CODE END -->
I'd also recommend using a class to denote whether the lightbox is visible or not, rather than changing the display property directly; that way it's more clear when you check it. Compare $el.is('.active') with $(el).css('display') == 'inline'

Related

How to hide a popup by clicking outside using javascript

There are so many questions like my one,even I go through this link also.But I didnt get a proper solution yet.So Im posting my issue here.
I have to popup a message when click an icon and when I click the same div where the icon is reside,it should disappear. This is working fine.But when I click outside the div also, the popup should disappear.How can I modify this javascript function to achieve it
<div>
<h5 class="haead">Search for a product title
<div class="popup" onclick="myFunction5()"> <img class="qnicon" src="question.png">
<span class="popuptext" id="myPopup5">Search product.</span>
</div>
</h5>
</div>
<script>
function myFunction5() {
var popup = document.getElementById("myPopup5");
popup.classList.toggle("show");
}
</script>
The easiest way I've found that avoids any number of other problems you could encounter, is to put the popup on top of a 100% width/height div. That "disabler" div has the same click handler as the button that would ordinarily close the popup. So if the user clicks the "X" to close, the "Ok" button (or whatever you've got set up) or the area outside the popup, same effect, it closes.
That "disabler" div (it effectively disables the entire app except for the popup) can be completely clear, or translucent, by setting the opacity.
You put the "disabler" div at z = 9998, the popup at z = 9999 (just more CSS), and they'll always be on top. Note that this may not be necessary if all your content loads into a div that is already underneath the disabler (e.g. the router-outlet div in Angular), but I usually do it anyway.
Complete basic example. I typically make a component out of this and hook it into an event bus so I can pass data in and out of it (so I can change the position, style, messages, even what happens when you click the close button). If you get this code you should be able to use some approximation of it in any framework, etc.
<html>
<head>
<style>
.button {
text-align: center;
width: 100px;
height: 30px;
background-color: green;
border: 2px solid grey;
color: white;
margin: auto;
position: relative;
}
.disabler {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
z-index: 99998;
background-color: #000000;
opacity: 0.5;
}
.popup {
position: relative;
/* Center with whatever voodoo you like */
top: calc(50% - 150px);
left: calc(50% - 150px);
width: 300px;
height: 300px;
background-color: blue;
border: 2px solid grey;
z-index: 99999;
}
</style>
</head>
<body>
<div class="button" onclick="togglePopup ( )">
Show Popup
</div>
<div class="button" onclick="showAlert ( )">
Show Alert
</div>
<!-- This div is on top of everything except the popup div -->
<!-- It effectively disables the entire app except for the popup -->
<div id="disabler" class="disabler" onclick="togglePopup ( )"></div>
<!-- This div holds the popup -->
<!-- You can only close the popup by clicking the close button, or the disabler background -->
<!-- Clicking in the blue popup area doesn't do anything (intentionally) -->
<!-- Even though you can see other widgets through the disabler, they're all inaccessible -->
<!-- Try the show alert button to confirm -->
<div id="popup" class="popup">
<div class="button" onclick="togglePopup ( )">
Close Popup
</div>
</div>
<script type="text/javascript">
togglePopup ( ); // Hide them to start.
function togglePopup ( ) {
let disabler = document.getElementById ( 'disabler' );
disabler.style.display = disabler.style.display ? '' : 'none';
let popup = document.getElementById ( 'popup' );
popup.style.display = popup.style.display ? '' : 'none';
}
function showAlert ( ) {
alert ( 'Hey there!' );
}
</script>
</body>
</html>
Here is the way to do this:
Javascript
popup.addEventListener('click',function(e) {
// This is important to prevent the popup from inheriting the event since it
// is inside the body
e.stopPropagation();
});
var body = document.body;
body.addEventListener('click', function(e){
if(popup.classList.contains('show')) {
popup.classList.remove("show");
}
);
I wish this solves your problem
Edit
That didn't work because you have to structure your code properly like this:
HTML
<div id='popup-container'>
<!-- This all inside the popup -->
<h5 class="haead">Search for a product title</h5>
<div class="popup-data">
<img class="qnicon" src="question.png">
<span class="popuptext" id="myPopup5">Search product.</span>
</div>
Show Popup
</div>
Javascript
var popupContainer = document.getElementById('popup-container');
var body = document.body;
var showPopup = document.getElementById('show-popup');
showPopup.addEventListener('click', function(e) {
e.preventDefault();
popupContainer.classList.add('show');
});
popupContainer.addEventListener('click', function(e) {
e.stopPropagation();
});
body.addEventListener('click', function(e) {
if(popupContainer.classList.contains('show'))
popupContainer.classList.remove('show');
);

How do I get a currently visible (default hidden) slideToggle() .div to close when another is opened?

So I have close to what I would like to achieve, including having my slideToggle .divs close when I click anywhere off of the "link" divs (.click, .click2) with one glaring exception...
When I click "Link 1" it does what I'd like and displays .showup then if I click "Link 2" it also initially does what I'd like and displays .showup2 over .showup BUT I need .showup to close so that they aren't both open at the same time.
As you can see with my provided code this presents a problem bc with both "showup" divs already open if I then directly click "Link 1" again .showup remains hidden behind .showup2
Similarly, in the above example if I click "Link 2" first, .showup2 opens but when I then directly click "Link 1", .showup does not appear over .showup2
So ultimately I would like my slideToggle divs to hide when I click ANYWHERE outside of my "Link" divs (.click and .click2) - which it currently does - however that ANYWHERE should include my other script instructed "Link" divs!! And that is where I am stumped.
Here is code that demonstrates in a very simplified example :
HTML
<div class="click">Link 1</div> <div class="click2">Link 2</div>
<div class="showup">something I want to show</div>
<div class="showup2">something else I want to show</div>
SCRIPT
$(document).ready(function(){
$('.click').click(function(event){
event.stopPropagation();
$(".showup").slideToggle("fast");
});
});
$(document).on("click", function () {
$(".showup").hide();
});
$(document).ready(function(){
$('.click2').click(function(event){
event.stopPropagation();
$(".showup2").slideToggle("fast");
});
});
$(document).on("click", function () {
$(".showup2").hide();
});
CSS
body{margin:50px;}
.showup,
.showup2 { width:100%;height:100px; background:red; display:none; position: fixed;}
.click,
.click2 { cursor:pointer; display:inline-block; padding: 0 15px;}
Thanks so much for any help! Jorie
You could do with same class name of the button and boxes .data-target attr used for target the which element to toggling .
Updated
Toggle function with each button
Bold text toggle function added
$(document).ready(function() {
$('.click').click(function(event) {
event.stopPropagation();
if($(".showup").eq($(this).attr('data-target')).css('display') == 'block'){
$(".showup").eq($(this).attr('data-target')).slideUp();
$('.click').removeClass('bold')
}
else{
$(".showup").hide();
$('.click').removeClass('bold')
$(".showup").eq($(this).attr('data-target')).slideToggle("fast");
$(this).toggleClass('bold')
}
});
}).on('click',function(){
$(".showup").hide();
$('.click').removeClass('bold')
})
body {
margin: 50px;
}
.showup{
width: 100%;
height: 100px;
background: red;
display: none;
position: fixed;
}
.bold{
font-weight:bold;
}
.click{
cursor: pointer;
display: inline-block;
padding: 0 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="click" data-target="0">Link 1</div>
<div class="click" data-target="1">Link 2</div>
<div class="showup">something I want to show</div>
<div class="showup">something else I want to show</div>

Onclick, only parent div not subdiv

I'm playing around with building a basic modal window and i want it do dissapear when i click the edges. So my problem in it's most basic form:
<div style="width:100%;height:100%;" onclick="hideAll()">
Hide all onclick.
<div style="width:100px;height:100px;">
does not hide all onclick
</div>
</div>
What is the best way to achieve this? To use unnested divs? html/css magic?
HTML:
<div style="width:100%;height:100%;" class="outerModal">
Hide all onclick.
<div style="width:100px;height:100px;">
does not hide all onclick
</div>
</div>
JavaScript:
$(document).on("click", ".outerModal", function(evt) { //listen for clicks
var target = $(evt.target ||evt.srcElement); //get the element that was clicked on
if (target.is(".outerModal")) { //make sure it was not a child that was clicked.
//hide dialog
}
});
Example:
JSFiddle
When you hide the parent tag, it automatically hides the childen tag as well, You should first contain the child div into variable and after that hide the parent div and append that stored child div into parent tag something like this.
HTML
<div id="result">
<div style="width:100%;height:100%;" id="parentDiv" onclick="hideAll()">
Hide all onclick.
<div style="width:100px;height:100px;" id="childDiv">
does not hide all onclick
</div>
</div>
</div>
javaScript
function hideAll(){
var childDiv = document.getElementById('childDiv'); //contain child div
var parDiv = document.getElementById('parentDiv');
parDiv.style.display = 'none'; //hide parent div
parDiv.parentNode.appendChild(childDiv); //append child div
}
DEMO
Assuming that "parentDiv" is to be the background and "childDiv" is to be the actual modal content, the best way I have found is to separate the divs entirely.
HTML
<div id="parentDiv" onclick="hideAll()"> </div>
<div id="childDiv" >
does not hide all onclick
</div>
Javascript using jQuery
function hideAll(){
/* The Parent Div will hide everything when clicked, but the child won't */
$('#childDiv').fadeOut(1000, function(){
$('#parentDiv').fadeOut(1000);
});
}
CSS
#parentDiv {
background: black;
display: block;
position: fixed;
top: 0;
left: 0;
z-index: 100;
height: 100%;
width: 100%;
}
#childDiv {
display: block;
position: relative;
background: white;
height: 200px;
width: 200px;
z-index: 101
}
Here is a working example.
Hope this helps at all.
See this fiddle:
http://jsfiddle.net/eZp9D/
$(document).ready(function () {
$('#parentDiv').click(function (e) {
if ($(e.target).prop('id') == "parentDiv") {
$(this).hide();
}
});
});
You can use basic jQuery and style it accordingly with CSS.
Check this example.
If you want to have it disappear by clicking outside of the dialog window, make sure that onClick you perform this action:
$( "#dialog_id" ).dialog( "close" );

Show different popups from list.

I'm having an issue displaying popups with multiple items on the page. Essentially it is a vertical "list" of items down the page. So far I have two. When I click the first one, the first set of information displays correctly, but when I click the second item, it displays the first set of information on the popup. Any help is appreciated, thanks!
<p> <a class="show-popup" href="#">Manual Therapy</a></p>
<div class="overlay-bg">
<div class="overlay-content">
<h2>Manual Therapy</h2>
<p>FIRST SET OF INFORMATION DISPLAYED HERE</p>
<button class="close-btn">Close</button>
</div>
</div>
<a class="show-popup" href="#">LIST ITEM 2</a>
<div class="overlay-bg">
<div class="overlay-content">
<h2>Low Level LASER Therapy</h2>
<p>SECOND SET OF INFORMATION DISPLAYED HERE</p>
<button class="close-btn">Close</button>
</div>
</div>
And here is the CSS
.overlay-bg {
display: none;
position: fixed;
top: 0;
left: 0;
height:100%;
width: 100%;
cursor: pointer;
background: #000; /* fallback */
background: rgba(0,0,0,0.75);
}
.overlay-content {
background: #fff;
padding: 1%;
width: 700px;
height: 400px;
overflow:auto;
position: relative;
top: 15%;
left: 30%;
margin: 0 0 0 -10%; /* add negative left margin for half the width to center the div */
cursor: default;
border-radius: 4px;
box-shadow: 0 0 5px rgba(0,0,0,0.9);
}
and here is the JS
$(document).ready(function(){
// show popup when you click on the link
$('.show-popup').click(function(event){
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
$('.overlay-bg').show(); //display your popup
});
// hide popup when user clicks on close button
$('.close-btn').click(function(){
$('.overlay-bg').hide(); // hide the overlay
});
// hides the popup if user clicks anywhere outside the container
$('.overlay-bg').click(function(){
$('.overlay-bg').hide();
})
// prevents the overlay from closing if user clicks inside the popup overlay
$('.overlay-content').click(function(){
return false;
});
});
You need to wrap your second anchor inside a <p> tag, then you can change:
$('.overlay-bg').show();
to:
$(this).parent().next().show();
This will help you to target the .overlay-bg according to your clicked .show-popup anchor
Fiddle Demo
LIVE DEMO
Put inside the anchors href the ID of the desired popup content you want to see:
CSS:
.overlay-content {
display:none; /* NOTE THIS */
HTML: (USE ONLY ONE POPUP ELEMENT BUT MORE CONTENT ELEMENTS!)
<a class="show-popup" href="#cont1">Manual Therapy</a>
<a class="show-popup" href="#cont2">LIST ITEM 2</a>
<div class="overlay-bg">
<div id="cont1" class="overlay-content">
<h2>Manual Therapy</h2>
<p>FIRST SET OF INFORMATION DISPLAYED HERE</p>
<button class="close-btn">Close</button>
</div>
<div id="cont2" class="overlay-content">
<h2>Low Level LASER Therapy</h2>
<p>SECOND SET OF INFORMATION DISPLAYED HERE</p>
<button class="close-btn">Close</button>
</div>
</div>
jQ:
$(function(){
$('.show-popup').click(function(event){
event.preventDefault();
$('.overlay-bg,'+ $(this).attr('href')).show(); // Show overlay, but also
}); // the popup ID content
// taken from the anchor HREF
$('.overlay-bg, .close-btn').click(function(){
$('.overlay-bg, .overlay-content').hide();
});
$('.overlay-content').click(function(event){
event.stopPropagation();
});
});
doing this way, you could even have inside the popup only one CLOSE button, but I'll leave it to you,
I hope you get the general idea...
Also: take a look at this question: event.preventDefault() vs. return false
add a id to link, div and button what you want show.
<a class="show-popup" href="#" id="1">Manual Therapy</a></p>
<div class="overlay-bg" id="div_1">
<div class="overlay-content">
<h2>Manual Therapy</h2>
<p>FIRST SET OF INFORMATION DISPLAYED HERE</p>
<button class="close-btn">Close</button>
</div>
</div>
<a class="show-popup" href="#" id="2">LIST ITEM 2</a>
<div class="overlay-bg" id="div_2">
<div class="overlay-content">
<h2>Low Level LASER Therapy</h2>
<p>SECOND SET OF INFORMATION DISPLAYED HERE</p>
<button class="close-btn">Close</button>
</div>
</div>
and use $(this) and the id.
<script>
$(document).ready(function(){
// show popup when you click on the link
$('.show-popup').click(function(event){
var id = $(this).attr("id");
event.preventDefault(); // disable normal link function so that it doesn't refresh the page
$('#div_'+id).show(); //display your popup
});
// hide popup when user clicks on close button
$('.close-btn').click(function(){
var id = $(this).attr("id");
$('#div_'+id).hide(); // hide the overlay
});
// hides the popup if user clicks anywhere outside the container
$('.overlay-bg').click(function(){
$(this).hide();
})
// prevents the overlay from closing if user clicks inside the popup overlay
$('.overlay-content').click(function(){
return false;
});
});
</script>

How to open different content in popups on clicking html links

I am using following code.I want to open different content on click.
<style>
#overlay_form {
position: absolute;
border: 5px solid gray;
padding: 10px;
background: white;
width: 270px;
height: 190px;
}
#pop {
display: block;
border: 1px solid gray;
width: 65px;
text-align: center;
padding: 6px;
border-radius: 5px;
text-decoration: none;
margin: 0 auto;
}
</style>
Following javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//open popup
$("#pop").click(function () {
$("#overlay_form").fadeIn(1000);
positionPopup();
});
//close popup
$("#close").click(function () {
$("#overlay_form").fadeOut(500);
});
});
//position the popup at the center of the page
function positionPopup() {
if (!$("#overlay_form").is(':visible')) {
return;
}
$("#overlay_form").css({
left: ($(window).width() - $('#overlay_form').width()) / 2,
top: ($(window).width() - $('#overlay_form').width()) / 7,
position: 'absolute'
});
}
//maintain the popup at center of the page when browser resized
$(window).bind('resize', positionPopup);
</script>
I want to use something like following html
<html>
<div>
<a href="#" id="pop" >Product Overview</a>
<br/>
<div id="overlay_form" style="display:none">
<a href="#" id="close" >Close</a>
</div>
<a href="#" id="pop" >User Interface</a>
<div id="overlay_form" style="display:none">
<a href="#" id="close" >Close</a>
</div>
</div>
</html>
On clicking different links I want to open different content in pop up.
Is is possible without repetition of whole java script with different ids.
Thanks
First of all you can't use the same id twice on the same page, you currently use #pop, #close and #overlay_form on both your links, update them with a class or different ids.
You could add a div inside each of your a tags that stores your content then just show/hide this on click?
There are a number of ways in which you could do this, but the simplest one that uses your existing code, requires switching a lot of your id's to classes. Something like this:
HTML
<html>
<div>
Product Overview
<div class="overlay_form" id="popup1" style="display:none">
<a href="#" class="close" >Close</a><br />
Popup1 text.
</div>
User Interface
<div class="overlay_form" id="popup2" style="display:none">
<a href="#" class="close" >Close</a><br />
Popup2 text.
</div>
</div>
</html>
JS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//open popup
$(".pop").click(function () {
var targetPopup = $(this).attr('popup-id');
$("#" + targetPopup).fadeIn(1000);
positionPopup(targetPopup );
});
//close popup
$(".close").click(function () {
$(this).closest(".overlay_form").fadeOut(500);
});
});
//position the popup at the center of the page
function positionPopup(targetPopup) {
$("#" + targetPopup).css({
left: ($(window).width() - $('#overlay_form').width()) / 2,
top: ($(window).width() - $('#overlay_form').width()) / 7,
position: 'absolute'
});
}
//maintain the popup at center of the page when browser resized
$(window).bind('resize', positionPopup);
</script>
This approach lets you use the class attribute to define a larger group of items that share the same behavior (as well as styles :) ), while still supporting the "uniqueness" of each popup.
Note: this makes use of a custom attribute (popup-id) which will not validate unless you update your DOCTYPE declaration to include it. Many people simply overlook that issue, though, particularly since HTML5 is adding support for custom attributes.
EDIT: forgot to mention . . . since you are changing your IDs to classes here, you will also need to update your CSS #pop and #overlay_form to .pop and .overlay_form.

Categories

Resources