0

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);
}
noob
  • 3
  • 4
  • 1
    did you link the js file properly? If you did can you please check it with another browser. – Mowazzem Hosen Aug 18 '20 at 04:31
  • Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) –  Aug 18 '20 at 04:34
  • Thanks guys, these suggestions helped me a lot. – noob Aug 21 '20 at 01:06

2 Answers2

0

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

kelvin
  • 1,480
  • 1
  • 14
  • 28
0

defer your script tag or put your script at the end of body

Akin Zeman
  • 447
  • 7
  • 9