What's Going on with My Code for the Hamburger Menu?

I am attempting to create a simple hamburger menu using either jQuery or JS, but unfortunately my code is not functioning as expected. I am struggling to identify the issue.

The layout consists of a hamburger icon on the top-left, a logo in the middle, and a profile/basket on the top-right corner.

Currently, I am focusing on getting the navigation list to appear upon clicking the burger icon, after which I can proceed with styling it accordingly. My approach involves utilizing the .hidden class to display the navigation as a block element when the burger icon is clicked.

Below is the provided code:

HTML:

<section class="header-section">
  <div class="header-container">
    <div class="header-content">
      <div class="hamburger-container">
        <i id="burger" class="fas fa-bars fa-2x"></i>
      </div>
      <div class="header-logo-container">
        <h2>Logo goes here</h2>
      </div>
      <div class="header-profile-and-signin">
        <i class="fas fa-user-circle fa-2x"></i>
        <i class="fas fa-suitcase-rolling fa-2x"></i>
      </div>
      <ul id="nav">
          <li>
            <a href="search-page.html" style="text-decoration: none">Holidays</a>
          </li>
          <li>
            <a href="sign-in.html" style="text-decoration: none">Sign In / Register</a>
          </li>
      </ul>
    </div>
  </div>
</section>

CSS:


body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.header-section {
  height: 100px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #999;
}

/* Styles for other elements */

#burger {
  cursor: pointer;
}

jQuery:


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

<script>
$("#burger").click(function() {
  $("#nav").toggleClass("hidden");
});
</script>

I would greatly appreciate any assistance. Thank you.

Answer №1

You've got a few issues with your code that need fixing:

  • $('burger') should actually be $('#burger') to correctly target elements using the id selector prefix
  • Similarly, $('nav') needs to be changed to $('#nav')
  • The CSS class .hidden should be more specific like #nav.hidden, and you might want to consider renaming it to .visible for clarity. However, this is more of a semantics issue.

Another thing to check is if you need to include a document.ready event handler in your JavaScript logic, depending on where it's located within the page. This will ensure that the jQuery code runs only after the DOM has finished loading.

jQuery(function($) {
  $("#burger").click(function() {
    $("#nav").toggleClass("hidden");
  });
});
/* Your CSS styles go here */
<!-- Your HTML structure goes here -->

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

What are some ways to customize the default Head tag in Next.js?

After using create-next-app to create a basic page, I decided to style the index.js page. I added a navigation bar within the header and now I'm trying to customize it. I've been wondering if there's a way to style the custom Head tag in Ne ...

Can a direct link to a Redis server be established through a web browser?

Can a connection be established with a redis server directly from the browser? In node, you can create a TCP connection using var client = net.connect(port, host);. I'm curious if it's possible to achieve the same in the browser either through Br ...

Implementing json value extraction in javascript

Hello there! I'm currently having trouble constructing a JSON format. Here is the JSON response: { "txs": { "lock_time": 0, "ver": 1, "size": 372, "inputs": [ { &qu ...

What is the best way to split two divs in this manner?

Is there a way to split two divs like this in such a manner using TailwindCSS? Alternatively, what would be the CSS code for dividing these two divs? I am struggling with this concept and cannot wrap my head around how it can possibly be achieved. ...

I am having trouble accessing the div. What could be causing this issue?

Here is the code I have written: - <html> <head> <title>Pranav Sharma</title> <style> @import url(http://fonts.googleapis.com/css?family=Lato:300,400,700); body { background: #ecf0f1; font-fami ...

How come AngularJS $onChanges isn't able to detect the modification in the array?

What is the reason behind Angular's failure to detect changes in an array, but successfully does so after changing it to null first? In my AngularJS component, I utilize a two-way data binding to pass an array. The parent component contains a button ...

Ways to permit https://* within a content security policy (CSP) configuration

I'm currently incorporating CSP into my website but encountering an issue with the img-src header. I'm using NodeJS and Express to develop the site for my Discord Bot, and I want to revamp it but I've hit a roadblock. ====== This is the co ...

Discovering character entities within a string using nodejs

There is a string below <!-- document.write("<a rel='nofollow' href='mailto:&#116;&#114;&#97;&#110;&#113;&#117;&#97;&#110;&#103;&#100;&#105;&#101;&#117;&#50;&#55;&#48;& ...

Vue's push() method is replacing existing data in the array

I'm currently facing an issue where I am transferring data from a child component, Form, to its parent component, App. The data transfer is functioning correctly, however, when attempting to add this data to the existing array within the App component ...

The class 'ConsoleTVsChartsCharts' could not be located

Attempting to implement Laravel charts using the package consoletvs/charts:6.*, Utilizing service providers ConsoleTVs\Charts\ChartsServiceProvider::class, With an alias: 'Charts' => ConsoleTVs\Charts\Charts::class, ...

Using a PHP variable within an AJAX modal window: A step-by-step guide

The main page (main.php) is currently holding a variable called $var = "hello". A modal window (modal.php) is being loaded through AJAX utilizing the following script: var modal_xhr = $.ajax({ 'type' : 'GET', ...

Error encountered when applying filter function in AngularJS/JavaScript due to syntax issue

Encountering an issue with the filter method in AngularJS/Javascript. Below is the code snippet: var temp = []; $scope.mulImage = $scope.mulImage.filter((x, i) => { if(temp.indexOf(x.filename) < 0) { temp.push(x.filename); retur ...

Asynchronous Node operations with Promise.all

When working on a basic JS program, I encountered the need for asyncOperation2 and asyncOperation3 to run in sequence with asyncOperation1. The specific order of execution required is either 1,2,3 or 2,3,1. Additionally, after completing these operations, ...

How to display content in separate divs using jQuery hover functionality

I'm in the process of creating my online portfolio by using bootstrap and jquery. I have a series of images arranged side by side with each other, and I want to make the description for each image appear when that specific image is hovered over. Each ...

Is there a method in Selenium/Appium to verify the success or failure of a click event after interacting with a button?

Is it possible to verify the click action on a WebElement after clicking in selenium/Appium just like how we can verify text? Is there a way to confirm that the click action was successful on web elements? ...

Align labels to the right in a Bootstrap 4 modal

Is there a way to align this label to the right? Currently, it only aligns to the left. I tried overriding the default value in Bootstrap 4 from justify-content: center to justify-content: right !important;, but it still remains on the left. What can I do ...

Verify the image aspect ratio using ngModel

Incorporating Angular 5 and Bootstrap, I've crafted a form that enables users to associate an image with a URL. My aim is to constrain this image to adhere to a specific aspect ratio. The smallimagelink input signifies the ngModel I'm utilizing. ...

Problem with a method in a JavaScript object

I am currently working on creating a List object that includes methods for adding tasks and loading items from a url. The add method pushes a task object onto the tasks array, while the load method retrieves data from a specified URL. However, I encounter ...

Accessing the nested arrays within an ng-repeat loop

Can anyone help me figure out what I'm doing incorrectly here? I've fetched some data and passed it to a controller as 'productInfo'. While I can successfully load the data, I am encountering issues when trying to target specific valu ...

What could be causing the observable collection to display the correct number of objects, yet have them all appear empty?

I am offering the following service @Injectable() export class LMSVideoResulful { getVideos( enrolmentId : number ) :Observable<Array<Video>> { var x = new Array<Video>(); //https://www.youtube.com/embed/MV0vLcY65 ...