Salih Erikci
Salih Erikci

Reputation: 5087

Javascript if/else not working as expected

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:

JsFiddle

<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

Answers (2)

Stuart
Stuart

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

Weafs.py
Weafs.py

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

Related Questions