0

I have an element with an id of "sd-nav-bar" with display: inline-block,

and I have a button that (after clicking on it) will hide that element if it is shown and vice versa using hider function.

but the hider function which contains two Ifs didn't work at all.

let hider = () => {
    let nav = document.querySelector('#sd-nav-bar');  
    if( nav.style.display == 'inline-block' ) {
        nav.style.display = 'none'
    }
    else if( nav.style.display == 'none' ) {
        nav.style.display = 'inline-block';
    };
}

and after i replaced the 2nd if by 'else statment' it worked, the code that woked is :

let hider = () => {
    let nav = document.querySelector('#sd-nav-bar');  
    if( nav.style.display == 'inline-block' ) { 
        nav.style.display  = 'none'
    }
    else {
        nav.style.display = 'inline-block';
    }
};

So why is this happening ? is the second IF wrong? or i just have to use else statment here and why ?

biberman
  • 5,606
  • 4
  • 11
  • 35
Abdoun abdou
  • 41
  • 1
  • 6

2 Answers2

1

The answer to this one is pretty straight forward. If the else/if-variant isn't working it means that non of the conditions matches.

nav.style will return an object containing only the inline styles. You've probably set the initial #sd-nav-bar style in a stylesheet, in which case it is not present within the inline style. For this reason nav.style.display will return an empty string, which matches neither 'inline-block' nor 'none'.

const nav = document.querySelector("#sd-nav-bar");
console.log("display:", nav.style.display);
#sd-nav-bar {
  display: inline-block;
}
<div id="sd-nav-bar"></div>

To match the computed value of display, use getComputedStyle().

const nav = document.querySelector("#sd-nav-bar");
const computedStyle = getComputedStyle(nav);
console.log("display:", computedStyle.display);
#sd-nav-bar {
  display: inline-block;
}
<div id="sd-nav-bar"></div>
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
0

I think the problem is the wrong semicolon before the last closing curly bracket - it should be behind it like in your second code snippet:

let hider = () => {
    let nav = document.querySelector('#sd-nav-bar');  
    if( nav.style.display == 'inline-block' ) {
        nav.style.display = 'none'
    }
    else if( nav.style.display == 'none' ) {
        nav.style.display = 'inline-block';
    }
};
biberman
  • 5,606
  • 4
  • 11
  • 35
  • 1
    Add console.log(nav.style.display) after the let, and you’ll see. My guess is, well why guess, run the modified program and find out. – jmoreno Apr 17 '21 at 12:26
  • in fact as the answer above shows. i can't use style.display since the styles are in an external stylesheet – Abdoun abdou Apr 17 '21 at 13:07