简体   繁体   中英

Works in codepen.io, but not in Visual Code Studio?

This line of code works in codepen.io, but not in visual code studio. When I open up a html file with link to the js in chrome, an error shows up that the my var nav is null, but when I used the code in codepen.io. The code works. I am trying to get a sidebar to appear and disappear when you click

let nav = document.querySelector('nav')
function toggleNav() {
  if (nav.classList.contains('is-open')) {
    nav.classList.remove('is-open')
  } else {
    nav.classList.add('is-open')
  }
}

here is the hmtl:

<button onclick="toggleNav()"> Click me for side bars </button>
<nav class="" >
    <a href="#">This is a link</a>
    <a href="#">This is a link</a>
    <a href="#">This is a link</a>
    <a href="#">This is a link</a>        
</nav>

and here is the css if you want to see what is-open is:

body {overflow:hidden}
a {
    border-width: 2px 4px 2px 4px ;
    text-decoration: none;
    margin: 0px;
    margin-top: 10px;
    padding: 5px;
    display: block;
    width: auto;
    height: 30px;
    border: solid brown;
    color: brown;
    background-color: darkgrey;
    margin: 0px;
}

.is-open {
    transform: translateX(-300px);
}

Try adding it to function like this !!

function toggleNav() {
  let nav = document.querySelector('nav')
  if (nav.classList.contains('is-open')) {
    nav.classList.remove('is-open')
  } else {
    nav.classList.add('is-open')
  }
}

Or
Just add JS at the bottom of the Page. When your Js code will be executed it will look for the 'nav' and it won't be able to find it when your page has just started to load.

Check this Answer for more details: https://stackoverflow.com/a/1829934/3995126

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