I have constructed an accordion which just works fine but I want to close this if someone clicks outside the element in JavaScript
I tried to add a click listener that captures click outside the div and turn its display to off but it doesn't work as it considers the link itself an outside of the div link and thus stops opening the div
function toggleaccordition() {
var link = document.getElementById('acrd_link');
var accrdion = document.getElementById("acc");
link.classList.toggle('active');
accrdion.classList.toggle('active');
}
nav ul {
display: flex;
}
nav ul li {
display: block;
margin-right: 20px;
margin-left: 2px;
list-style: none;
text-decoration: none;
}
nav ul li a {
text-decoration: none;
}
#acrd_link.active {
text-decoration: underline;
color: deepskyblue;
}
.accrd {
display: block;
height: 0px;
width: 450px;
color: blue;
opacity: 0.0;
transition: opacity 0.5s;
transition: height 0.5s;
padding-top: 30px;
position: relative;
z-index: 4;
background: #ff0036;
}
.internal {
background: gray;
}
.internal span {
color: yellow;
}
.accrd>* {
display: none;
}
.accrd.active {
display: block height: 500px;
opacity: 1.0;
transition: height 1s;
transition: opacity 1s;
}
.accrd.active>* {
display: block;
}
<nav>
<ul>
<li><a href="#">xxxxxxx</a></li>
<li><a href="#" id="acrd_link" onclick="toggleaccordition()">Click two open/close accordion</a></li>
<li><a href="#">yyyyyyyy</a></li>
</ul>
</nav>
<div class="accrd" id="acc">
<div class="internal">
This is my accordion that works fine.<span>I just want this to be closed when i click outside this accrdion<span></div>
</div>