Skip to content
Advertisement

Website javascript doesn’t work unless I’m using LiveServer on VSCode to load it?

Navbar toggle isn’t working?

Javascript:

const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]

toggleButton.addEventListener('click', () => {
    navbarLinks.classList.toggle('active')
})

HTML

    <div class="navbar">
        <div class="brand-title">
          <h1>LIST CONVERT</h1>
        </div>
        <a href="#" class="toggle-button">
            <span class="bar"></span>
            <span class="bar"></span>
            <span class="bar"></span>
        </a>
        <div class="navbar-links">
            <ul>
                <li class="selected"><a href="#">SQL List</a></li>
                <li><a href="add-zeroes-or-characters-to-list.html">Expand Item Size</a></li>
                <li><a href="about.html">About</a></li>
            </ul>
        </div>
    </div>

When I am using liveserver on VSCode the navbar menu created by this works perfectly, however when I simply open the file from my finder into the browser, the navbar no longer works?

Here is the CSS in case that’s necessary:

.navbar {
  display: flex;
  color: var(--white);
  justify-content: space-between;
  background-color: var(--darkblue);
  align-items: center;
}

.brand-title {
  margin: 0.5em;
  font-family: "Oswald", sans-serif;
  text-transform: uppercase;
  font-size: 1.6rem;
}

.navbar-links ul {
  margin: 0;
  padding: 0;
  display: flex;
}

.navbar-links li {
  list-style: none;
}

.navbar-links li a {
  text-decoration: none;
  color: white;
  padding: 1.3rem;
  display: block;
}

.navbar-links li:hover {
  background-color: var(--primaryblue);
}

.navbar-links .selected {
  background-color: var(--primaryblue);
}

.navbar-links .selected-light {
  background-color: var(--lightblue);
}

@media (max-width: 600px) {
.navbar {
    flex-direction: column;
    align-items: flex-start;
  }
  .toggle-button {
    top: 20px;
  }
  .navbar ul {
    display: flex;
    flex-direction: column;
    width: 100%;
  }
  .navbar-links {
    display: none;
    text-align: center;
    width: 100%;
  }
  .navbar-links.active {
    display: flex;
  }
  .navbar-links .selected-light {
    background-color: var(--darkblue);
  }
}

I’m just now getting into implementing CSS and JavaScript into HTML, sorry if the code isn’t the best! Still got a lot of work to do!

Advertisement

Answer

Like Jaromanda X said, some things dont work when opening a file without using an HTTP server. If you press F12 on your web browser to open developer tools, and check on the console you may see some errors there.

If you are using chrome, you can install an extension like this one which creates a local web server to test that kind of stuff. There are a lot of other options as well, like the VSCode one.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement