简体   繁体   中英

Using JS if statement to change div class with button (what am I doing wrong)?

 function navtoggle(elementRef) { if (document.getElementById('nav').className = 'closed') { document.getElementById('nav').className = 'open' } else if (document.getElementById('nav').className = 'open') { document.getElementById('nav').className = 'closed' }; } 
 .closed { display: none; } .open { display: block; } #navget { width: 100px; height: 100px; box-shadow: 0px 0px 15px black; } 
 <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> <title>HTML Library</title> </head> <body> <div id="nav" class="closed"> <ul> <li><a href="index.html"><h1>HOME</h1></a> </li> </ul> </div> <button onclick="JavaScript: navtoggle(this);" id="navget">NAV</button> </body> </html> 

Here is the Html:

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css">
        <title>HTML Library</title>
    </head>
    <body>
        <div id="nav" class="closed">
            <ul>
                <li><a href="index.html"><h1>HOME</h1></a></li>
            </ul>
        </div>
 <button onclick="JavaScript: navtoggle(this);" id="navget">NAV</button>
    </body>
</html>

The JS:

function navtoggle(elementRef){
if (document.getElementById('nav').className = 'closed') 
    {document.getElementById('nav').className = 'open'}

else if (document.getElementById('nav').className = 'open')
    {document.getElementById('nav').className = 'closed'};

}

And the CSS:

.closed {
    display: none;
}

.open {
    display: block;
}

#navget {
    width: 100px; height: 100px;
}

I know that it would be easier to just use a checkbox, and I do know how to do that. However, I want it to just be a button so that I can make it look better and such. I'm rather new to JS so please do not be too harsh for the dumb question. Thank you.

in conditional statement you have use "=" instead of compare "=="

 if (document.getElementById('nav').className == 'closed') {
    document.getElementById('nav').className = 'open'
  } else if (document.getElementById('nav').className == 'open') {
    document.getElementById('nav').className = 'closed'

you have several problems in your sintax I made you a plunker here so you can see all the details, but basically:

function navtoggle(elementRef){
  if (document.getElementById('nav').className === 'closed')  {
    document.getElementById('nav').className = 'open'
  }
  else if (document.getElementById('nav').className === 'open'){
    document.getElementById('nav').className = 'closed'
  } //You was using semicolon here and that wasn't parsing well
}

I don't know if miss to add the script in the header also but let me know if it worked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM