I'm encountering a new issue with a menu I'm working on. My goal is to hide the menu when the user clicks outside of it. The challenge lies in the fact that the menu is always visible but translated to the right of the element, making it not directly visible in the DOM.
The problem persists with the button not functioning as expected and the menu activating even when clicking on the screen. My attempts to verify the visibility of the div are ineffective. I've tried using the getBoundingClientRect()
function suggested by many, but I'm currently stuck with
document.body.contains(MyElement)
.
Here is my JavaScript:
function myFunction(x) {
x.classList.toggle("change");
document.getElementById("dropdown-meniu-content").classList.toggle("show");}
$(document).click(function(event) {
if ( document.body.contains(document.getElementById('dropdown-meniu-content') ) ) {
if(!$(event.target).closest('#dropdown-meniu-content').length) {
document.getElementById("dropdown-meniu-content").classList.toggle("show");
document.getElementById("buton-meniu").classList.toggle("change");
}
}
}
The CSS:
.logo {
float: left;
margin-top: 10px;
margin-left: 5px;
width: 200px;
height: 100px;
}
.meniu {
float: right;
width: auto;
}
.buton-meniu {
display: block;
cursor: pointer;
width: 35px;
margin-right: 30px;
margin-top: 40px;
}
.bar1, .bar2, .bar3 {
width: 35px;
height: 5px;
background-color: black;
margin: 6px 0;
transition: 0.4s;
}
.change .bar1 {
-webkit-transform: rotate(-45deg) translate(-9px, 6px);
transform: rotate(-45deg) translate(-9px, 6px);
}
.change .bar2 {
opacity: 0;
}
.change .bar3 {
-webkit-transform: rotate(45deg) translate(-8px, -8px);
transform: rotate(45deg) translate(-8px, -8px);
}
.dropdown-meniu {
position: relative;
display: inline-block;
}
.dropdown-meniu-content {
top: 110px;
position: fixed;
background-color: #d6d6d6;
width: 30%;
max-width: 10000px;
height: 100%;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
overflow: hidden;
right: 0;
transform: translateX(100%);
transition: transform 0.5s ease;
}
.show {
transform: translateX(0%);
}
Here's the HTML:
<div class="meniu">
<div class="dropdown-meniu">
<div id="buton-meniu" class="buton-meniu" onclick="myFunction(this)">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
<div id="dropdown-meniu-content" class="dropdown-meniu-content">
<div class="dropdown-ferestre">
<div id="buton-ferestre" class="buton-ferestre">Ferestre</div>
<div id="dropdown-ferestre-content" class="dropdown-ferestre-content">
<p id="demo"></p>
</div>
</div>
</div>
</div>
</div>
If you prefer not to go through the code, you can also view the JSFiddle here: https://jsfiddle.net/1qrtb424/18/
Thank you for your assistance!