How to hide a popup by clicking outside using javascript - 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');
);

Related

How do i make the input to show infobox even when i click on the show button without glitching

I have a code where I am showing a infobox when user clicks on an input field. This works fine but to make the UX better I would like the infobox to remain open when user clicks on a show button. It shouldn't close and open again
<div class="text-field">
<input type="text" class="username" name="username" placeholder="username" />
<button class="show-pwd">show</button>
</div>
<div class="info" style="display: none;">
<p>hello world</p>
</div>
$(function() {
const username = $('.username');
const showPwd = $('.show-pwd');
showPwd.click(()=>{
username.get(0).type = 'password';
$('.info').show();
});
$('.username').on("focus",(e)=>{
$('.info').show();
});
$('.username').on("blur",(e)=>{
$('.info').hide();
});
});
.text-field input {
border: none;
background-color: transparent;
}
.text-field {
background-color: lightblue;
width: 200px;
height: 25px;
}
.info {
background-color: lightgreen;
width: 200px;
height: auto;
}
heres the codepen
I tried to add the show method in click handler but that just adds a glitch
The blinking is happening because input blurring is triggered first, and then the button click.
You can avoid the blinking with a slight delay when blurring / moving out of the input, like in the following example.
const username = $('.username');
const showPwd = $('.show-pwd');
var btnClicked = false; // this is new
showPwd.click(()=>{
btnClicked = true; // this is new
username.get(0).type = 'password';
$('.info').show();
});
$('.username').on("focus",(e)=>{
$('.info').show();
});
$('.username').on("blur",(e)=>{
setTimeout(function() {
if(!btnClicked) {
$('.info').hide();
}
},100);
});
.text-field input {
border: none;
background-color: transparent;
}
.text-field {
background-color: lightblue;
width: 200px;
height: 25px;
}
.info {
background-color: lightgreen;
width: 200px;
height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-field">
<input type="text" class="username" name="username" placeholder="username" />
<button class="show-pwd">show</button>
</div>
<div class="info" style="display: none;">
<p>hello world</p>
</div>
One suggestion - since the current setup (and the original one) have no way of hiding the .info div once the button has been clicked, consider making your .show-pwd button a toggle button - one click to show the info div (if it's not visible), and another to hide it (if it's visible).
If you decide to do that, you would have to change my initial suggestion a bit, in order to avoid hiding the info div when moving from your input to your button.
And if you're up for some UX suggestions, you could change the show button - for example, you could use the open / closed eye icon to reflect what would happen on button click (similar to show / hide password in various online services, like Gmail, and the like).

Close lightbox on click outside of the child div

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'

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" );

How to scroll back to the top of page on button click?

I am creating my product pages by using the object tag code, but every time I click the "view" button, the next page is staying at the same position of previous page which I just viewed. How can I add functionality that will let me view from the top of page every time I click the "view" button?
<div id="container" class="clearfix"><!--! end of #sidebar -->
<div class="holder"></div>
<div id="content" class="defaults"><!-- navigation holder -->
<div id="title2">Office Section</div>
<!-- item container -->
<ul id="itemContainer">
<li>
<div id="product">
<div id="title">FuBangĀ®</div>
<div class="imageOuter" style="margin:0">
<a class="image" href="officesection010.html">
<span class="rollover" ></span>
<img class="imgborder" src="product/officesection/010.jpg" width="165" height="165" />
</a>
</div><br />
<div id="text">Sofa </div><br />
<div id="button">
View Details
</div>
</div>
</li>
</ul>
<br />
<div id="title2"></div>
<div class="holder"></div>
</div>
</div> <!--! end of #content -->
</div> <!--! end of #container -->
When I click the "View Details" button at a specific position "x" here: http://postimg.org/image/vgs0lwhtr/
The next page shows the same position "x", but I want it to jump to the top of page:
http://postimg.org/image/vn80e2lph/
Using Javascript:
document.body.scrollTop = document.documentElement.scrollTop = 0;
Using jQuery:
$(function() {
$('body').scrollTop(0);
});
jQuery(document).ready(function($){
$(window).scroll(function(){
if ($(this).scrollTop() > 50) {
$('#backToTop').fadeIn('slow');
} else {
$('#backToTop').fadeOut('slow');
}
});
$('#backToTop').click(function(){
$("html, body").animate({ scrollTop: 0 }, 500);
//$("html, body").scrollTop(0); //For without animation
return false;
});
});
please refere this, may this help
Sometimes placing scroll to body doesn't work if your current content is generated through jQuery (as it was in my case). In such situation you can just do following.
$(function() {
$('html').scrollTop(0);
});
A small issue with Subhash's jQuery solution is that you must call this code within $(document).ready() in order for your $('body') selector to work. The ready event may not fire before parts of your page have been rendered to the screen.
An better approach is to simply modify the user's location as a work-around to this browser 'feature':
//Above all of your $(document).ready(...) code
document.location = "#";
Simple HTML solution for jumping between page parts
// Place a tag like this where you would like to go
// in your case at the top
<a name="top"></a>
// you will reach there by click of this link better use an image reach their by clicking on this we can also use an image, align in right
last
Back to top button, works in all browsers.To change the scroll speed simply change the x in counter -= x here x = 10
function scrollToTop(){
var myBody = document.body;
var id = setInterval(secondFunction,1);
var height = window.pageYOffset;
var counter = height;
function secondFunction(){
if(window.pageYOffset == 0){
clearInterval(id);
}
else {
if(!!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g)){
counter -= 10;
counter--;
document.documentElement.scrollTop = counter;
}
else {
counter -= 10;
counter--;
myBody.scrollTop = counter;
}
}
}
}
body {
height: 5000px;
margin: 0;
padding: 0;
}
.backToTop {
position: fixed;
/* Fixed at page */
top: auto;
bottom: 20px;
left: auto;
right: 20px;
background-color: crimson;
color: white;
padding: 5px;
cursor: pointer;
}
header {
position: relative;
top: 0;
left: 0;
width: 100%;
height: 100px;
background-color: black;
}
<!-- back to top button -->
<span class="backToTop" onclick="scrollToTop()">TOP</span>
<!-- Header -->
<header>
</header>
Assign an id="#body" and tabindex in the <body> tag
<body id="#body" tabindex="1">
and use jquery focus()
$(function() {
$("#body").attr("tabindex",-1).focus();
}
You can use this method:
function gototop() {
if (window.scrollY>0) {
window.scrollTo(0,window.scrollY-20)
setTimeout("gototop()",10)
}
}

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