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.
0
give a positive ratinggive a negative rating
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.
Share on FacebookShare on TwitterShare on LinkedInSend email
1 answer
x
x
2024 AnswerTabsTermsContact us