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 .

This is how I can expect:

  • When I click labelLink


    if hiddenBox

    display = 'none'

    then change it to display = 'block'


    if hiddenBox

    display = 'block'

    then remove its focus blur()

    and set itdisplay='none'

  • When I press the button hiddenBox

    when it has focus, set the hiddenBox display='none'


    (This part works well.)

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>

      

+3


source to share


2 answers


Do it 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>
      

Run codeHide result


+2


source


As already pointed out, both event listeners interfere with each other. One way to fix this is to remove the listener on labelLink

when the hidden field is shown, and restore the listener with a little pause after the hidden hidden window. 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>
      

Run codeHide result


+1


source







All Articles