Get DIV ID onClick - to hide DIV when click outside in Javascript

How can I get the ID of specific DIV element using onClick event ? I have a couple of DIVs and I need to hide them when users click on the specific DIV that is used as a semi-transparent background. I am looking for a javascript solution.
07 Jan 2022 at 03:09 PM
0pnshow more
LarsLars
Hi,

To hide a DIV element with other DIV elements inside, when click on a specific DIV, you can use the javascript solution below. It compares if clicked element is the same as element identified with getElementById. This solution can be used for example on image preview.


<script>

document.onclick = function(e) {
var d = document.getElementById('first');
if(e.target == d) { d.style.display='none'; }
}

</script>

<div id='first'>
<div id='second'>Text</div>
</div>


When the "first" DIV is used as a full screen background with transparency and you click on the content in the "second" DIV, then nothing should happen. But when you click on the "first" DIV, the javascript function should hide both, the first and the second one.
07 Jan 2022 at 07:14 PM
0pnshow more
TimTim
Share on FacebookShare on TwitterShare on LinkedInSend email
Follow us on Facebook & Twitter
2022 AnswerTabsTermsContact us