Click on external div to hide div in pure JavaScript

I want to create a popup that should appear after clicking a button and disappearing after the user clicks on it.

I am not sure how to make a div disappear when I click on it.

var popbox = document.getElementById("popbox"); document.getElementById("linkbox").onclick = function () { popbox.style.display = "block"; }; ???.onclick = function () { popbox.style.display = "none"; }; 
+5
source share
3 answers

Here is the second version, which has a transparent overlay, as the author of the question asked in the comments ...

 window.onload = function(){ var popup = document.getElementById('popup'); var overlay = document.getElementById('backgroundOverlay'); var openButton = document.getElementById('openOverlay'); document.onclick = function(e){ if(e.target.id == 'backgroundOverlay'){ popup.style.display = 'none'; overlay.style.display = 'none'; } if(e.target === openButton){ popup.style.display = 'block'; overlay.style.display = 'block'; } }; }; 
 #backgroundOverlay{ background-color:transparent; position:fixed; top:0; left:0; right:0; bottom:0; display:block; } #popup{ background-color:#fff; border:1px solid #000; width:80vw; height:80vh; position:absolute; margin-left:10vw; margin-right:10vw; margin-top:10vh; margin-bottom:10vh; z-index:500; } 
 <div id="popup">This is some text.<input type="button" id="theButton" value="This is a button"></div> <div id="backgroundOverlay"></div> <input type="button" id="openOverlay" value="open popup"> 

Here is the first version ...

Here is the code. If there is anything else, please add let me know :)

An event object (e) provides access to event information. e.target gives you the element that raised the event.

 window.onload = function(){ var divToHide = document.getElementById('divToHide'); document.onclick = function(e){ if(e.target.id !== 'divToHide'){ //element clicked wasn't the div; hide the div divToHide.style.display = 'none'; } }; }; 
 <div id="divToHide">Click outside of this div to hide it.</div> 
+6
source
 el.onmouseleave = function(){ document.body.onclick = function(){ el.style.display = 'none'; document.body.onclick = null; } } 
0
source

Ok, here the jQuery based solution is based on any element pressed in the DOM.

 $('div').on('click', function(e){ var parents = $(e.currentTarget).parents(); for (var i = 0; i < parents.length; i++) { if (parents[i].id === 'divToHide' || e.currentTarget.id === 'divToHide') { // you are in the popup }; } e.stopPropagation(); }); 

It looks like your current element, as well as any of the parents, and checks if the identifier matches. If divToHide is in the parents () list, you can open a popup.

* NOTE: This requires wrapping the contents in a div wrapper or something similar.

-4
source

Source: https://habr.com/ru/post/1233454/


All Articles