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

Learn how to create a smooth and consistent horizontal image slider using JavaScript to manipulate transition transforms

Does anyone know how to create a seamless sliding effect for a series of images in Vuejs? Let's say we have images 1, 2, 3, 4, and 5 When the first slide occurs, the order of images should be: 2, 3, 4, 5, 1 For the second slide: 3, 4, 5, 1, 2 And ...

Vue.js encountered an uncaught TypeError while trying to execute the 'drawImage' function

I am facing an issue with my vue.js application where I can successfully apply a filter to a photo, but I am unable to post it. The error message I am encountering is: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingCon ...

The issue of the "port" attribute not working for remotePatterns in the Image component has been identified in Next.js 13's next.config.js

I've encountered an issue with the code snippet below. I'm attempting to utilize remotePatterns in my next.config.js file to enable external images. Strangely, when I set the port to an empty string "", it functions correctly. However, specifying ...

$filter is functioning correctly, however it is generating an error message stating: "Error: 10 $digest() iterations reached. Aborting!"

Here is an example of a JSON object that I am working with: { "conversations":[ { "_id": "55f1595d72b67ea90d008", "topic_id": 30, "topic": "First Conversation", "admin": "<a href="/cdn-cgi/l/e ...

Is it possible to validate an email domain using node.js? For example, checking if gmail.com is a valid email domain, and ensuring that users do not enter incorrect variations such as egmail.com

I've been working with React.js and Express.js/Node.js, utilizing nodemailer for sending emails. However, I've noticed that a lot of emails are coming in with incorrect domains, such as [email protected], rather than the correct ones like [e ...

Dynamic background featuring a tall vertical image

I have an image that is extremely long, measuring 2263 x 8192 pixels. I want to design a website with a background that spans the width of the window and the full height of the image, all while maintaining responsiveness. The concept is to have this elong ...

The contents within the div element exceed the width of its parent element

Hey there, I'm currently working on a Rails application to showcase some links in a horizontal layout. The links are indeed displaying horizontally without wrapping, just as intended. However, I've noticed that the containing div is wider than th ...

Is it possible to configure node js to send an array instead of a string?

How can I modify the code to return a 2D array of the results? For example: clothes = [[1, "name", "desc"], [2, "name2", "desc2]] Can the 'res' variable send a list directly or do I need to create a list after returning it? app.get('/post&ap ...

Accessing the current clicked item in $scope using an Angular Directive within ng-repeat

I have set up a custom directive called calendar which includes a date picker created in JQuery. To associate the ng-model with the date picker, I am using the following code successfully: var clickedID = "#" + $scope.indexid + "_datePicker"; $(clickedID ...

Interactive Video Effect

Seeking to create a unique video hover effect on an image where, when the mouse hovers over it, a video pops up similar to examples found on this website. I have been grappling with finding a solution for this issue over the past few months. Does anyone ...

Is there a bug with text rotation in CSS 3?

I'm having trouble understanding how text rotation works in CSS3. For example, when I try to rotate text like you can see here, the rotated text never seems to be in the correct location, despite setting properties like: right: 0; bottom: 0; There ...

altering the color of various spans consecutively

I am looking to create a text effect where each alphabet changes color in a wave-like pattern, starting from the left. I have assigned each alphabet a span with classes like span0, span1, and so on. To change the color, I used the following code: for (var ...

accessing past sign-ins with passport.js and express-sessions

I need some assistance with displaying a user's login history on the front-end of my webpage. I am using Express and storing sessions in mongoStore as shown below: app.use(session({ secret: process.env.SECRET, key: process.env.KEY, resave: fals ...

Centering multiple nested divs inside a parent div

I am experiencing an issue with center aligning several nested divs inside a container. The contents (nested divs) are not aligning properly within its parent element. <div id="parent"> <span id="menu_0" class="d"></span> <span ...

Attempt to efficiently register components automatically on a global scale in Vue by utilizing the powerful combination of Laravel-Mix and Webpack

In my previous projects with Vue, which were based in a Laravel-Mix/Webpack runtime environment, I used to individually register components and views as needed. This was done by importing them and extending Vue: import BaseButton from './components/Ba ...

Console displays null as the attribute value

When I check the console, I notice that the data-postid attribute is displaying 'null'. What could be causing this issue? I would like to view the data-id in the console when clicking on the button with the id modal-save. I have reviewed my cod ...

Angular template not refreshing automatically

Within my controller: $scope.deleteUser = function(user){ $.ajax({ url: "/users/" + user.id.toString(), method: "DELETE", success: function(result){ $scope.users = result["users"]; ...

Implementing a jQuery function to trigger window resize on window load

I'm facing an issue with my resize function where the contents within a window change when it reaches a certain width. I'm trying to achieve this same effect on window load but haven't been successful so far. Here's what I've attem ...

Having difficulty creating JSON data following retrieval of rows by alias in MySQL

I am encountering an issue while trying to fetch rows from two tables using a JOIN and aliases. The problem arises when I attempt to convert the fetched rows into JSON data and assign them to a JSON array. Below is the code snippet: $personal = $db->p ...

Approach for checking duplicates or empty input fields through PHP, AJAX, and JavaScript

Looking for a solution to validate and check for duplicate values when listing, creating, or deleting products using a REST API. I tried using rowCount in the php file to check for duplicates but I feel there might be a better approach that I am missing. N ...