0

Hi guys am trying to come up with javascript code thats popularly applied in detecting click area to close an element like a sidenav or a floating div whenever the user clicks outside the element, the click outside works and closes the element but whenever i click inside my element, it still dissappears, here is my code:

<script>
    var y = document.getElementById("advert");
    window.onclick = function(event){
        if (event.target == y){
            y.style.display = "none";
        } else {
            y.style.display = "block";
        }
    }
</script>
rossipedia
  • 56,800
  • 10
  • 90
  • 93
  • 1
    we need more info about your css and html – Gene Sy Feb 21 '20 at 14:57
  • 1
    Script alone doesn’t tell us much. Please go read [mre], and update your question accordingly. Without seeing the HTML structure, it is impossible to tell if this happens due to event bubbling not handled (resp. interrupted) correctly, or something else. – CBroe Feb 21 '20 at 14:57
  • The advert is an element is a div that floats at the center of the page on page load –  Feb 21 '20 at 15:00
  • https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element second answer is not jquery – epascarello Feb 21 '20 at 15:01
  • please provide a reproducible example – Quethzel Diaz Feb 21 '20 at 15:16

1 Answers1

0

I have made a small changes in your code, please try this one:

  var y = document.getElementById("advert");
  window.onclick = function(event){
    if (event.target == y || event.target.parentNode == y){
        y.style.display = "none";
    } else {
        y.style.display = "block";
    }
  }
harsh_apache
  • 433
  • 4
  • 10