The hamburger menu for the responsive navigation bar is not being shown on the screen

I am having trouble creating the "Hamburger menu" on my website. It looks fine, but when I click on it, nothing happens.

I have set up an event listener to detect any clicks on the button and toggle the class to display or hide the ul elements accordingly.

I can't seem to figure out what's wrong with the code. Is there a simpler solution?

const bar = document.getElementById('bar');
                const nav = document.getElementById('navbar');
                const close = document.getElementById('close');
                
                if (bar){
                    bar.addEventListener("click", () => {       
                        nav.classList.toggle("active");
                    })
                }
                
                if (close) {
                    close.addEventListener("click", () => {
                        nav.classList.remove("active")
                    })
                }
@import url('https://fonts.googleapis.com/css2?family=Spartan:wght@100;200;300;400;500;600; 700; 800; 900&display=swap');
                * {
                    margin: 0;
                    padding: 0;
                    box-sizing: border-box;
                    font-family: 'Spartan', sans-serif; 
                }
                
                h1 {
                    font-size: 50px;
                    line-height: 64px;
                    color: #222;
                }
                
                ...
                <!-- CSS Styles continue here -->
                ...
                footer .copyright {
                    width: 100%;
                    text-align: center;
                }
                
                /*Shop Page*/
                
                
                /*Single Product*/
                
                
                /*Blog Page*/
                
                
                /*About Page*/
                
                
                /*Cart Page*/
                
                
                /*Start Media Query*/
                
                @media (max-width:799px) {
                    ...
                }
                
<script src="https://kit.fontawesome.com/8848882185.js"></script>
<section id="header" ... >

Answer №1

It seems like you have made very few mistakes that are hard to notice. Please be more careful next time. Your <a> tag is missing an opener and there is also a space in your id.

<i id="bar "class="fa-solid fa-bars active"></i></a>

As a result, your

const bar = document.getElementById("bar");

is null

To correct this, change it to

 <a><i id="bar"class="fa-solid fa-bars active"></i></a>

Everything else looks fine.

const bar = document.getElementById("bar");
const nav = document.getElementById("navbar");
const close = document.getElementById("close");

if (bar) {
  bar.addEventListener("click", () => {
    console.log("bar click event");
    nav.classList.toggle("active");
  });
}

if (close) {
  close.addEventListener("click", () => {
    nav.classList.remove("active");
  });
}
@import url('https://fonts.googleapis.com/css2?family=Spartan:wght@100;200;300;400;500;600; 700; 800; 900&display=swap');
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Spartan', sans-serif; 
}
...
...

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

NServicebus JavaScript message handler: Enhancing Communication

I am in the process of developing a JavaScript event subscriber for NServicebus, and I am seeking feedback on my approach as well as any potential pitfalls to watch out for in this design. My proposed components are as follows: ASP.NET MVC BusControll ...

The PHP DOM feature is inserting an additional <p> element along with <html> and <body> tags

When it comes to displaying different images for desktop and mobile users based on their device, I have implemented a function in my index.php file. The code snippet from my index.php file: <!DOCTYPE html> <html class="no-js" lang="en"> <h ...

Adding Logging Features in ASP.NET

I am currently working with an .ascx file that contains both JavaScript and div elements. I need to add a log statement inside a function for troubleshooting purposes. Can someone please guide me on how to achieve this? Below is a snippet of my code: fu ...

Attempting to implement a multi-select input field using AJAX

I am attempting to save multi-select input using ajax in a Laravel application, but I keep encountering the following error: {message: "Function name must be a string", exception: "Error", …} Below is my Blade code: <select class= ...

Troubleshooting the issue of jQuery Ajax failing to deliver a PDF

I have been attempting to use jquery, ajax, and django to download a pdf file. Here is my code from the views.py file in Django: if request.POST.get('action') == 'download_labels': order_list = json.loads(request.POST. ...

Ways to determine if a textbox is empty and trigger a popup notification with jQuery

I'm having trouble with checking if the textbox is empty in my form. Every time I try to submit, instead of receiving an alert message saying "Firstname is empty," I get a message that says "Please fill out filled." ('#submit').click(func ...

altering the directory for bower installations on specific repositories exclusively

Recently, I've been experimenting with Bower and at the same time exploring Polymer. If you want to download polymer elements using bower, you can use the following command: bower install --save PolymerElements/iron-image I assume there's a sp ...

Retrieve a particular element from a JavaScript object by iterating through it with the .each()

Welcome, fellow developers! I am currently facing a challenge in my ticketing system project involving getting the 'title' variable from a node.js loop. The objective is to use this variable as a placeholder so that when a user wants to edit a t ...

Issue with React Material-UI drawer not functioning properly when invoking a child component function from the parent

Here is a piece of code I have for the App.js file: import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import Child from './child'; class App extends Component { render() ...

Organizing Object Array by Key in Typescript: A Step-by-Step Guide

How can I sort an array of candidate objects in TypeScript within Angular 2 by the name property? candidateid:number; name:string; ...

Transform a string date in the format of YYYY-MM-DD into a Date object while maintaining the original date within the user's specific timezone

Currently, I am facing a challenge in trying to convert a string date formatted as YYYY-MM-DD into a date object that can be manipulated with matDatePicker. The issue that arises is that the date displayed always shows yesterday's date. After some inv ...

Adjust the HTML layout based on the JSON data provided

I am working with a JSON script that contains live matches, which change every 5 minutes. The changes could involve keys such as live_in or score. Matches are also being deleted and added to the JSON. I want to ensure that my HTML output remains updated at ...

Error encountered: angular-php API unavailable following the minification process

After setting up a basic angular-php yeoman app to experiment with, I encountered an issue. angular-php Running grunt serve functioned correctly and retrieved data using rest with $http.get('/api/features').... However, upon minifying the proj ...

Is there any issue that you can spot with this js / jQuery code?

Presented below is a script that prompts the user to confirm clicking a button based on a system setting. The system setting is saved in a hidden field established from the code-behind. Markup: <asp:HiddenField ID="hfConfirmOnApproval" runat="server" ...

The feature of filtering in Telerik software

I have a piece of JavaScript code that is supposed to run when the document is ready. However, when I apply telerik filtering, the function that should run on document ready is not working after the filter is applied. $(document).ready(function () { ...

Exploring the world of 3D with wireframes and unique object materials

I need to retrieve the wireframe of an object that I have loaded using OBJMTLLoder. Below is the code snippet I am currently using: var loader = new THREE.OBJMTLLoader(); loader.load( 'obj/male02/male02.obj', 'obj/male02/mal ...

Enable Sound when Hovering over Video in React Next.js

I am currently facing an issue while trying to incorporate a short video within my nextjs page using the HTML tag. The video starts off muted and I want it to play sound when hovered over. Despite my best efforts, I can't seem to get it working prope ...

The variable named "$file" has been assigned an invalid value {}; Please upload a valid value

I'm currently utilizing GraphQLClient from graphql-request for sending requests to my server. I'm attempting to upload a file using the following code: const graphQLClient = new GraphQLClient('http://localhost:4000/graphql', { crede ...

utilizing Typescript object within an array of objects

How can I optimize typing this nested array of objects? const myItem: Items[] = [{ id: 1, text: 'hello', items: [{ id: 1, text: 'world' }] }] One way to approach this is by using interfaces: interface It ...

What is the correct way to use setInterval in a React component's constructor?

I'm trying to set an interval when the main component renders. I attempted to do this in the constructor like so: constructor(props) { super(props); this.props.fetchUserInfo(); this.props.fetchProducts(); setInterval(console.log(&a ...