I created a toggle button to display some navigation links on mobile screens, but it requires two clicks upon initial page load. After the first click, however, it functions correctly. How can I ensure that it operates properly from the start?
Below is the script containing the function:
script.js
function ToggleNavLinks() { /
var navLink = document.getElementsByClassName("nav-links")[0];
if (navLink.style.display === "none") {
navLink.style.display = "flex";
}
else {
navLink.style.display = "none";
}
}
Here's the layout file that includes the front-end element. I have already tested the external script reference, and it works fine.
layout.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{title}}</title>
<meta charset="utf-8"/> <!-- Charset -->
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel='stylesheet' href='/stylesheets/style.css'/>
<script type="text/javascript" src="/javascripts/script.js"></script>
</head>
<body>
<header>
<nav class="navbar">
<img class="logo" alt="logo" src="images/logo-stock.png">
<a class="nav-toggle" onclick="ToggleNavLinks()" >
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</a>
<div class="nav-links">
<ul>
<li>
<a href="#">Home</a>
</li>
<li>
<a href="#">Projects</a>
</li>
<li>
<a href="#">Contact</a>
</li>
</ul>
</div>
</nav>
</header>>
<div>
{{{body}}}
</div>
</body>
</html>
Also included below is the stylesheet:
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap');
:root {
font-size: 16px;
font-family: 'Roboto', sans-serif;
--text-primary: white;
--text-secondary: #4c6bc1;
--bg-primary: #101316;
--bg-secondary: #181a1d;
}
* {
box-sizing: border-box;
}
body {
background-color: var(--bg-primary);
margin: 0;
padding: 0;
}
body::-webkit-scrollbar {
width: 0.25rem;
}
<!-- Stylesheet continues... -->