Tips for creating a toggle menu using JavaScript

I am trying to create a toggle menu using CSS and JavaScript, but I have encountered an issue where clicking on the bars displays the navbar, but then the bars disappear and there is no option to close the navbar.

 <a href="#" class="fas fa-bars" id="menu-icon"></a>
        <a href="#" class="logo">flower<span>.</span></a>

        <nav class="navbar">
            <a href="#home">home</a>
            <a href="#about">about</a>
            <a href="#contact">contact</a>
            <a href="#shop">shop</a>
        </nav>
 let menuIcon = document.querySelector('.fa-bars');
        let menu = document.querySelector('.navbar');

        // Add event listener to the menu icon
        menuIcon.addEventListener('click', () => {
            menuIcon.classList.toggle('fa-bars');
            menu.classList.toggle('open');
        });
  header .fa-bars{
        display: block;
    }
    header .navbar{
        position: absolute;
        top: 100%; left: 0; right: 0;
        background: #eee;
        border-top: .1rem solid rgba(0, 0, 0, .1);
        display: none;
    }
    header .navbar a{
        padding: 1.5rem;
        margin: 1.5rem;
        background-color: #fff;
        border-top: .1rem solid rgba(0, 0, 0, .1);
        display: block;
        border-radius: .5rem;
    }

    header .navbar.open{
        display: block;
    }

This code works to show the navbar but does not provide a way to close it. When I try to run it, the toggle shows the navbar but doesn't allow for closing it by clicking again.

Answer №1

By toggling the classList, you have the ability to modify the current state of the classes assigned to the specific element. For a more detailed explanation, you can refer to this resource.

In the scenario provided, the class being toggled is fa-bars, which corresponds to the element linked to the click event. Therefore, clicking on fa-bars will result in the removal of the class, causing it to be hidden. To resolve this issue, simply eliminate the initial statement within your click event.

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

Display with organized information, Arrange with unprocessed data in DataTables.net

Below is a snippet of the datatables configuration I am working with: { "dom" : "rltip", "processing" : true, "serverSide" : false, "order" : [ [ 1 , "desc" ] ], "searching" : false, data: [ { "column-a" : "Samp ...

The plumber encountered an issue and triggered a custom error function, resulting in an error in the 'plumber' plugin: Error message: Unable to connect to undefined

Currently, I am developing a Wordpress theme starter application using node, gulp, and handlebars to generate templates. I am running into an issue with the integration of plumber, notify, and gulp-sass plugins. If you are interested in checking out my w ...

Strings holding special arrangements of breaks in between

Currently, I am developing a portal that enables examiners to provide a problem statement, sample input, and sample output. However, I am facing an issue where the sample input/output values are stored as complete strings, causing line breaks to not render ...

Importing classes in ECMAScript 6 does not work properly, causing issues when running scripts

I am currently learning Selenium Webdriver. I am facing an issue where I can't run a script with imported classes, but I am able to run it without classes using import functions only. To execute it, I use babel-cli in the following manner: node ./babe ...

Encountering a glitch while setting up gulp-sass

I'm encountering an error specifically when trying to install gulp-sass. Other modules, like gulp-livereload, install without any issues. I'm currently using npm version 6.0.0. Below is the relevant section in my package.json: "devDependencies ...

Activate function when list item is clicked

My goal is to execute a function when users click on the li elements in the snippet below without relying solely on onclick. For instance, clicking on the first li element (with a value of 1) should trigger a function where the value "1" is passed as an ar ...

Hiding or closing a modal in Angular JS

I am encountering difficulties when trying to close the Modal in Angular JS HTML <div class="container"> <div class="col-md-12" id="gridSet"> <div class="gridStyle adjustViewPort" ng-grid="gridOptions"></div&g ...

Navigating SEO strategies for client-side components in Next.js with text content to optimize search engine rankings

I'm currently developing a Next.js application that involves a single shared audio file and multiple text components. Each text component corresponds to a specific timestamp in the audio, updating its state to stay active and highlight when the audio ...

Encountering 404 Errors while Attempting to Reach API Endpoint in an Express.js Application Hosted on cPanel

I have a Node.js application running on cPanel, and I'm facing 404 errors when trying to access an API endpoint within my app. Let me provide you with the setup details: Directory Structure: public_html/ server.mjs index.html node_modules ...

Using a string array item to add a line break in HTML will be ineffective

Issue Resolved with Updated Code After entering text in the edit text field to be searched on the textview, the text is highlighted in color. However, all line breaks are removed, causing all the text to appear in one sentence. This problem occurs only wh ...

Unveil the Expressjs middleware within the API Client

I am currently developing a Nodejs API Client with the following simple form: //client.js function Client (appId, token) { if (!(this instanceof Client)) { return new Client(appId, token); } this._appId = appId; this._token = tok ...

Unable to create property within array in model

I am facing an issue while trying to access the name property of an array called Model[] generated from my Model.ts file. When attempting to use it in my app.component, I receive an error stating that the property 'name' does not exist on type Mo ...

Having issues with the integration of Sweet Alert and $_session variables

I am having trouble getting a sweet alert to show when the SQL condition is true. Below is the code for the back-end implementation. <?php include "../../../config/config.php"; if (isset($_POST['submit-slider'])) { $title = $_POST[&apos ...

Bespoke HTML, CSS, JavaScript, and PHP website designs within the Wordpress platform

I am a beginner in the world of Wordpress, coming from a background of creating websites from scratch. Currently, I am working on a Wordpress template (Astra) and looking to create a custom page using HTML, CSS, JavaScript, and PHP from the ground up to ad ...

Video streaming platform without the need for javascript and plugins

Is it feasible to watch Youtube videos without relying on javascript and plugins, exclusively using HTML5 or a similar alternative? ...

Stylish slanted divs achieved using Bootstrap 4

I'm currently in the process of constructing a block with 6 slanted divs using Bootstrap. Take a look at the image provided below: https://i.sstatic.net/vvg0b.png After attempting to use rows and columns, I noticed that they weren't aligning co ...

Retrieve the status of a CSS animation using JavaScript and display it within an element or log it to the console for future modifications

I am experimenting with CSS3 animations to create a marquee effect and want to trigger a function when the animation changes from running to paused or initial state. HTML: <div class='animationBackground'><p id="marqueeText">Scrolli ...

Having issues with my Bootstrap navigation dropdown - any suggestions on what I might be overlooking?

I'm having trouble getting the bootstrap dropdown and button to function properly when the menu collapses on tablet or mobile view. Below is my HTML code for the navigation: <nav class="navbar navbar-default navbar-fixed-top"> <div c ...

The functionality of Directive hinges on the use of a template

I am exploring a more web-component approach to using Angular. As part of this, I have developed an http-request directive with url and response attributes. The implementation is successful, but I find that my directive relies on a template unnecessarily. ...

Tips for synchronizing the indexes of two arrays using a common value in JavaScript

Is there a way to sort one array to match the order of another array with identical content, based on a shared property? For instance: let firstArray = [{id: 123, ...}, {id: 456, ...}, {id: 789, ...}] // always in this order let secondArray = [{id: 456, . ...