Reputation: 5087
I am trying to toggle a hidden menu with a link. But when i click on the link, it reopens the hidden menu instead of closing it.
Here is how i expect it to run:
When i click labelLink
if hiddenBox
's display = 'none'
, then change it to display = 'block'
if hiddenBox
's display = 'block'
, then delete its focus by blur()
and set it display='none'
When i click outside of the hiddenBox
when it has the focus, set hiddenBox 's display='none'
(This part is working well.)
<ul>
<li>
<a id="labelLink" href="#"
onclick="
if(document.getElementById('hiddenBox').style.display === 'block'){
document.getElementById('labelLink').focus();
document.getElementById('hiddenBox').style.display ='none';
}
else{
document.getElementById('hiddenBox').style.display = 'block';
document.getElementById('hiddenBox').focus();
}
return false;"
>
Click Me
</a>
<div id="hiddenBox" tabindex="-1"
onblur="document.getElementById('hiddenBox').style.display ='none';"
>
I was hidden
</div>
</li>
</ul>
Upvotes: 3
Views: 108
Reputation: 9858
As already pointed out, the two event listeners are interfering with each other. One way of fixing this is to remove the listener on labelLink
when the hidden box is shown, and restore the listener with a slight pause after the hidden box is hidden again. JSFiddle
var labelLink = document.getElementById('labelLink'),
hiddenBox = document.getElementById('hiddenBox');
labelLink.addEventListener('click', showBox);
hiddenBox.addEventListener('blur', hideBox);
function showBox(){
hiddenBox.style.display = 'block';
hiddenBox.focus();
labelLink.removeEventListener('click', showBox);
}
function hideBox() {
hiddenBox.style.display = 'none';
labelLink.focus();
window.setTimeout(function() {
labelLink.addEventListener('click', showBox);
}, 500);
}
<a id="labelLink" href="#" >Click Me</a>
<div id="hiddenBox" tabindex="-1" style="display:none" >I was hidden</div>
Upvotes: 1
Reputation: 22992
Do it this way instead.
var labelLink = document.getElementById('labelLink');
var hiddenBox = document.getElementById('hiddenBox');
labelLink.addEventListener('click', function() {
hiddenBox.style.display = hiddenBox.style.display == 'block' ? 'none': 'block';
});
labelLink.addEventListener('blur', function() {
hiddenBox.style.display = 'none';
})
#hiddenBox {
display: none
}
<ul>
<li><a id="labelLink" href="#">Click Me</a>
<div id="hiddenBox" tabindex="-1">I was hidden</div>
</li>
</ul>
Upvotes: 2