What steps can I take to design a functional hamburger menu?

After multiple attempts to create a hamburger menu, I have hit a roadblock. Clicking on the menu icon transforms it into an 'X', but unfortunately, it does not trigger the opening of the menu. Despite days of effort and research, I have yet to find a solution that actually works.

Below is the HTML code for the navmenu and hamburger icon:

let menu = document.querySelector('#menu-icon');
let navmenu = document.querySelector('.navmenu');

menu.onclick = () => {
  menu.classList.toggle('bx-x');
  navmenu.classList.toggle('open');
}
.navmenu {
  display: flex;
}

.navmenu a {
  color: #000;
  font-size: 16px;
  text-transform: capitalize;
  padding: 10px 20px;
  font-weight: 400;
  transition: all .42s ease;
}

.navmenu a:hover {
  color: #03A9F4;
}

.nav-icon {
  display: flex;
  align-items: center;
}

.nav-icon i {
  margin-right: 20px;
  color: #ffffff;
  font-size: 25px;
  font-weight: 400;
  transition: all .42s ease;
}

.nav-icon i:hover {
  transform: scale(1.1);
  color: #03A9F4;
}

#menu-icon {
  font-size: 35px;
  display: none;
  color: #ffffff;
  z-index: 10001;
  cursor: pointer;
}

@media(max-width: 750px) {
  #menu-icon {
    display: block;
  }
  .navmenu {
    position: absolute;
    top: -100%;
    right: 0%;
    width: 300px;
    height: 130vh;
    background: #000;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 120px 30px;
    transition: all .42s;
  }
  .navmenu a {
    display: block;
    margin: 10px 0;
  }
  .navmenu.open {
    right: 0%
  }
}
<a href="#" class="logo"><img src="images/logo5.png" alt="" class="prevent-select"></a>
<ul class="navmenu">
  <li><a href="#" id="prevent-select" class="hover-underline-animation">Home</a></li>
  <li><a href="#" id="prevent-select" class="hover-underline-animation">Shop</a></li>
  <li><a href="#" class="hover-underline-animation" id="prevent-select">Sale</a></li>
  <li><a href="#" class="hover-underline-animation" id="prevent-select">Contact</a></li>
  <li><a href="#" class="hover-underline-animation" id="prevent-select">Policies</a></li>
  <li><a href="#" class="hover-underline-animation" id="prevent-select">More</a></li>
</ul>
<div class="nav-icon">
  <a href="#" id="prevent-select"><i class='bx bx-search-alt-2'></i></a>
  <div class="dropdown2">
    <button class="dropbtn2">
                        <a href="#" id="prevent-select"><i class='bx bx-user'></i></a>
                    </button>
    <div class="dropdown-content2">
      <div class="login">
        <ul>
          <a href="login_register.php" id="prevent-select">Log in/Register</a>
        </ul>
      </div>
    </div>
  </div>
  <a href="#" id="prevent-select"><i class='bx bx-shopping-bag'></i></a>
  <div class="bx bx-menu" id="menu-icon"></div>
</div>

Although I attempted the provided approach, it did not yield the intended result. My goal is to achieve a sliding effect to open the menu upon clicking the hamburger menu icon.

Answer №1

Feel free to refer to this as a demonstration

const toggleBtn = document.querySelector('.toggle-btn');
const content = document.querySelector('.content');

toggleBtn.addEventListener('click', () => {
  toggleBtn.classList.toggle('active');
  content.classList.toggle('active');
});
/* Toggle button */

.toggle-btn {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  padding: 10px;
  margin-right: 20px;
}

.toggle-btn span {
  width: 30px;
  height: 4px;
  background-color: #333;
  margin-bottom: 5px;
  transition: all 0.3s ease-in-out;
}

/* Toggle button animation */

.toggle-btn.active span:nth-child(1) {
  transform: translateY(10px) rotate(45deg);
}

.toggle-btn.active span:nth-child(2) {
  opacity: 0;
}

.toggle-btn.active span:nth-child(3) {
  transform: translateY(-10px) rotate(-45deg);
}

/* Slide content */

.content {
  position: fixed;
  top: 0;
  right: -100%;
  width: 250px;
  height: 100vh;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
  padding: 50px 20px;
  transition: all 0.3s ease-in-out;
}

.content li {
  margin-bottom: 20px;
}

.content a {
  display: block;
  font-size: 20px;
  font-weight: bold;
  color: #333;
  text-decoration: none;
  transition: color 0.3s ease-in-out;
}

/* Slide content animation */

.content.active {
  right: 0;
}

.content.active a:hover {
  color: #f00;
}
<header>
  <nav>
    <div class="toggle-btn">
      <span></span>
      <span></span>
      <span></span>
    </div>
    <ul class="content">
      <li><a href="#">Home</a></li>
      <li><a href="#">About</a></li>
      <li><a href="#">Services</a></li>
      <li><a href="#">Contact</a></li>
    </ul>
  </nav>
</header>

Answer №2

@MohammedMalek's design may be slightly superior to this one, but here is another example for your consideration

function toggleMenu() {
    document.getElementById("menu").classList.toggle("active");
}
.container{
  width: 300px;
  border: 1px solid black;
  overflow: hidden;
}

.hamburger{
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  cursor: pointer;
}

.line{
  height: 4px;
  width: 100%;
  background-color: black;
  border-radius: 2px;
}

.line::before{
  height: 4px;
  width: 100%;
  background-color: black;
  margin-top: -8px;
  content: '';
  display: block;
  border-radius: 2px;
}

.line::after{
  content: '';
  height: 4px;
  width: 100%;
  display: block;
  background-color: black;
  margin-top: 12px;
  border-radius: 2px;
}

.list{
  transform: translateX(-100%);
  border: 1px solid black;
  transition: transform .5s;
}

.list.active{
  transform: translateX(0%);
}
<div class="container">
  <div class="hamburger" onclick="toggleMenu()">
    <div class="line">

    </div>
  </div>

  <div id="menu" class="list">
    <ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
    </ul>
  </div>
</div>

You can also explore CSS-only solutions online for this issue - I personally prefer the JavaScript version for simplicity, but it's always good to have options.

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

How can I retrieve items from an object that are contained within a nested array with a specific value

I am working with a nested array of objects, and I am trying to extract matching items based on a specific value stored in the nested object within these objects, which also contain nested arrays. Example: Sample data: const items = [ { name: & ...

The fixed position seems to be malfunctioning and behaving more like absolute

I have a simple question. I am currently designing a mobile version of a page, and we are trying to keep the "snag it" yellow button fixed at the bottom. However, the 'position: fixed' property is not working as expected; it's behaving like ...

What's Next? Redirecting Pages in Node.js Express after Handling POST Requests

Is it possible to redirect to a different page from a post request? module.exports = function(app) { app.post('/createStation', function(request, response){ response.redirect('/'); //I'm having trouble getting ...

Is server-side rendering necessary for `browserHistory` in React Router?

I am a beginner in the world of React and currently diving into the complexities of routing. While hashHistory (/#/paths/like/this) proves to be functional, browserHistory (/paths/like/this) appears much cleaner. However, I noticed that when reopening URLs ...

How to implement an instance method within a Typescript class for a Node.js application

I am encountering an issue with a callback function in my Typescript project. The problem arises when I try to implement the same functionality in a Node project using Typescript. It seems that when referencing 'this' in Node, it no longer points ...

Error encountered when attempting to retrieve JSON data in JavaScript due to being undefined

A snippet of code that reads and writes JSON data is presented below: var info; $(function () { $.getJSON("data.json", function (d) { info = d; }); $('.btn').click(function () { info['c-type'] = $('#c- ...

How can one remove surrounding paragraph texts using BeautifulSoup in Python?

I'm a beginner in Python, working on a web crawler to extract text from articles online. I'm facing an issue with the get_text(url) function, as it's returning extra unnecessary text along with the main article content. I find this extra te ...

"An error occurs when trying to trigger a .click() event within a list element

There is a list that can contain either plain text or a link. If there is a link present, the entire list element should be clickable. When attempting to execute the following code: if ($('.link').length) { $('li[data-contains-link]' ...

To enable the radio button upon clicking the list item in JavaScript, simply check the radio button

I am working with radio buttons Here is the HTML code: <input type="radio" class="first" name="bright" checked> <input type="radio" class="second" name="bright" > <input type=" ...

Increasing the upward motion of the matrix raining HTML canvas animation

Recently, I've been experimenting with the Matrix raining canvas animation here and I was intrigued by the idea of making it rain upwards instead of downwards. However, my attempts to achieve this using the rotate() method resulted in skewing and stre ...

What is the Significance of the Height in This Sample Menu?

I came across this interesting menu sample on W3Schools while working on my MVC layout page. My menu was looking messy, and I really liked the clean look of this one. When I pasted it into my website, it worked perfectly, but I'm puzzled about how it& ...

What is the best way to send a JSON object in Vue.js?

<template> <div id="app"> <div id="bee-plugin-container"></div> </div> </template> <script> // import axios from "axios"; // import Bee from "@mailupinc/bee-plugin"; import $ from 'jquery' ...

Optimizing web content for iOS Safari with min-height media queries

I'm currently working on a Bootstrap-based photo browser that needs to have a responsive 4:3 aspect ratio. To achieve this, I have implemented the following approach: #carousel { width: 320px; height: 240px; ... } Additionally, I utilize media ...

Passing form values from JavaScript to a JSP page - a comprehensive guide

I am working on a sample HTML page that includes inline JavaScript for calculating geocodes and retrieving latitude and longitude values. My question is, how can I submit all the form values along with the latitude and longitude returned from the showlocat ...

Incorporating object into main function of VueJS root component

I have integrated VueJS into my HTML template for an application. When a button is clicked, it passes the object of a component to its root in the following manner: <button v-on:click="$root.savePlan(dataObj)"></button> The dataObj is passe ...

What is the best way to send an array of objects to a Node.js server?

What is the method for sending an array of objects with user data to the server for verification? I am attempting to pass orderform data to a server for validation and then display it on a different page after redirection. const addProductsToServer = (ev ...

Why does my Node.JS Express request return undefined after submitting a post request from a form?

Having trouble retrieving data from an HTML form using Node.JS/Express. The req.body seems to be empty, returning an undefined value. Node const express = require('express') const bodyParser = require('body-parser') const app = express ...

Whenever I attempt to implement NavigationContainer in react native, an error always pops up

Hey there! I'm currently diving into the world of React Native and decided to start with a small project. However, I've encountered a persistent error when trying to use the NavigationContainer. Here's the error message I keep getting: error ...

CSS based on conditions for 2 specific divs

Hello, I am working on an HTML page where I need to apply CSS only if certain conditions are met. The div with the id "flipbook-page3-front" will always be present on this HTML page. Sometimes, another div with the id "pagesFlipbook" may also appear on t ...

"Troubleshooting issue: jQuery AJAX encountering problems with parsing JSON

I recently came across a Uncaught SyntaxError: Unexpected end of input error in my code. var dataURL = "LineChartController?tp=" + tpAtt + "&dept=" + dept + "&date=" + dateMY; alert(dataURL); var JSONdata = jQuery.aja ...