The toggle button requires two clicks to activate

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... -->

Answer №1

element.style.display === 'none'

is considered true when the element has an inline style attribute that includes display: none. It's important to note that this holds true regardless of the actual computed style property of the element. You can verify this in the following example:

console.log(document.querySelector('.test').style.display);
.test {
  display: block !important;
}
code {
  background-color: #eee;
}
<div style="display: none;" class="test">I have <code>style.display === 'none'</code>. You are looking at me. Please stop staring, it's not nice.</div>

To check for the computed property of the display, use

window.getComputedStyle(element).display === 'none'

In summary, replace

if (navLink.style.display === "none") {

with

if (window.getComputedStyle(navLink).display === "none") {

Answer №2

Perhaps the issue does not lie within your JavaScript code. Before anything else, inspect your CSS file. Verify if the display property in your code is set to none or flex. If it is already set to a different value, that may be why it isn't working initially.

 .navlink{
display: none;
}

Adjust it to :

 .navlink{
display: flex;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the value of the following element

In the table, each row has three text fields. <tr> <td><input type="text" data-type="number" name="qty[]" /></td> <td><input type="text" data-type="number" name="ucost[]" /></td> <td><input ty ...

What is the best way to create a nullable object field in typescript?

Below is a function that is currently working fine: export const optionsFunc: Function = (token: string) => { const options = { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, } ...

Storing formatted user input in an array with VueJS: A step-by-step guide

Looking for assistance that relates to the following question Vue.js: Input formatting using computed property is not applying when typing quick I am facing a challenge in extracting formatted values from text inputs and storing them in an array. I intend ...

What is the process for displaying all indexes of a Mongo Collection using MongoDB Node native?

I am curious about how to retrieve all indexes from a specific collection in mongodb. I've tried using listIndexes, indexes, and indexInformation, but these methods only return empty values (arrays and objects). However, when I run db.getCollection(&a ...

Can you explain the execution process of this Http.post method and provide details about the code path it follows

As I delve into the world of web development, one aspect that has me stumped is the functionality of the Http.post section within a project I stumbled upon on GitHub. Specifically, this pertains to an ExpressJS with Typescript repository I came across. So, ...

Utilizing Node.js with Redis for organizing data efficiently

Currently, I am in the process of configuring a Redis cache system for storing incoming JSON data in a specific format. My goal is to create an ordered list structure to accommodate the large volume of data that will be stored before eventual deletion. Th ...

What is the best way to wrap a call to XMLHttp Request within a $q promise?

I am trying to figure out how to wrap the following code in an AngularJS ui-router resolve section with a $q promise. The goal is to return success or fail based on whether the http request works. Should I encapsulate all of this inside a promise or just ...

Styling elements with CSS when the cursor hovers over them

I have a unique design challenge where I have stacked elements - an image, text, and an icon. My goal is to make only the icon animate when any of these elements are hovered over. <style> .hvr-forward { display: inline-block; vertical-align: mi ...

Transmit information from Ajax to CodeIgniter's controller

Right now, I am facing an issue with sending data from my JavaScript to a function in the controller using AJAX. Despite my best efforts, AJAX is not sending the data. Below, you can find the code that I have been working on: The JavaScript Function var ...

Using conditional rendering within the map function in React

I am working with the code snippet below and I am looking to implement a conditional rendering to exclude index 0 from being displayed. How can I achieve this? return ( <section> {pokemonCards.map((pokemon, index) => ...

What are the steps to fixing the date time issue between NextJS and Firebase?

I am facing an issue with Firebase Database returning timestamps and unable to render them into components using Redux. How can I resolve this error and convert the timestamp to a date or vice versa? I need help with valid type conversion methods. import ...

Guide to utilizing an Ajax response object

Here is the code I am using to display data based on values selected from dropdowns: $("#botao-filtrar").click(function(){ $(".mask-loading").fadeToggle(1000); $.ajax({ url: 'datacenter/functions/filtraDashboardGeral.php', as ...

transferring information from child to parent with the help of Vue.js and Laravel

As a newcomer to vue.js, I have a child component called 'test' and a parent component called 'showdata'. My issue arises when I try to emit data from the child to the parent - while the emission is successful, displaying the data in th ...

Tips on displaying the appropriate object value in a text field based on the selection from a dropdown menu

In my Ruby on Rails form, I have a dropdown menu with various category names: <td> <div class="div1"> <%= f.collection_select(:category_id, Category.all, :name, id: 'category_select', :include_blank => & ...

Create an animated underline for two CSS tabs

I'm interested in learning how to create a similar animation using JS, jQuery, or Vue Transitions with Bootstrap. I want to achieve the effect of moving the line under TAB1 to the right when TAB2 is clicked. Can anyone guide me on animating the div sm ...

Strategies for sorting data in d3js/dimplejs visualizations

I am looking to enhance the interactivity and responsiveness of a d3js/dimplejs chart by implementing filtering based on clicks in the legends for different series. The code I tried below did not hide the series as expected, although it worked well with a ...

Reveal the hidden div by sliding it up from the bottom

I have a container with brown branches resembling the image, and I'm looking to hide it. When a button is clicked, I want it to reveal from the bottom to the top, almost like it's being unmasked. I've ruled out a typical bottom-up slide anim ...

JSON response is not being successfully passed in PHP Ajax form validation

I've been struggling to solve my code for the past few days but haven't had any success. I'm attempting to validate my login form using AJAX, however, it seems like there's an issue with my Jquery AJAX script. Every time I try, the con ...

Having trouble adding a track to a playlist on Spotify with a post request using fetch API

Struggling to post a track URI and playlist ID to the Spotify API in order to add a track to a playlist. Utilizing URL parameters and adding one track at a time based on Spotify's guidance that states 'The Spotify URIs of the tracks to add can b ...

Listening to LayersControl.Overlay checkbox clicks in React-Leaflet: A guide

My goal is to dynamically render overlay controls and bind a click event listener to the checkbox of each control in React. However, I am unsure how to provide a React ref to LayersControl or an onClick handler to LayersControl.Overlay. Is there a more eff ...