Problem Related To Parent And Child Element
I am a newbie in Javascript coding. I wanted to do a mobile menu where if I click outside of the menu - the menu will disappear. I have done it successfully. Now the problem is whe
Solution 1:
The problem here is
if (event.target.parentNode !== disappear ){
disappear.className = "topnav";
}
when you are clicking on the icon( i tag) the parent node is the anchor tag. so its true. I have changed the code to below. And this should work for your example, also check the whole code snippet below
if (event.target.parentNode !== disappear && event.target.parentNode.parentNode !== disappear)
<!DOCTYPE html><html><head><metaname="viewport"content="width=device-width, initial-scale=1"><linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"><style>body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
.topnav {
overflow: hidden;
background-color: #146875;
}
.topnava {
float: left;
display: block;
color: #ffffFF; /*font color*/text-align: center;
padding: 14px16px;
text-decoration: none;
font-size: 17px;
}
.topnava:hover {
background-color: #00e5ff; /*top nav menu back hover color*/color: black;
}
.topnav.icon {
display: none;
}
@media screen and (max-width: 900px) /* Mobile Screen Breakdown */
{
.topnava:not(:nth-child(-n+3)) {
display: none;
}
.topnava.icon {
float: right;
display: block;
}
}
@media screen and (max-width: 900px) {
.topnav.responsive {position: relative;}
.topnav.responsive.icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsivea {
float: none;
display: block;
text-align: left;
}
}
</style></head><body><divclass="topnav"id="myTopnav" ><ahref="#home">Home</a><ahref="#floorplan">about Us</a><ahref="#address">Address</a><ahref="javascript:void(0);"class="icon"onclick="myFunction()"><iclass="fa fa-bars"></i></a></div><script>functionmyFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
var disappear = document.getElementById('myTopnav');
window.onclick = function(event) {
if (event.target.parentNode !== disappear && event.target.parentNode.parentNode !== disappear){
disappear.className = "topnav";
}
}
</script></body></html>
Post a Comment for "Problem Related To Parent And Child Element"