My CSS seems to be causing an issue and preventing the function from running correctly. Now I just need to

I'm currently working on a project and following a tutorial to help me create a navigation bar. The tutorial I am using can be found here: https://www.youtube.com/watch?v=gXkqy0b4M5g. So far, I have only reached the 22:05 mark in the video.

I have successfully constructed the HTML, CSS, and initial JavaScript function that is supposed to display the navbar when clicking on the hamburger menu created from div elements. Despite having no errors in my code and everything being an exact match with the tutorial, the function fails to execute when I click the hamburger menu.

console.log("Hello!");

const navSlide = () => {
  const burger = document.querySelector(".burger");
  const nav = document.querySelector(".nav-links");

  burger.addEventListener('click', () => {
    nav.classList.toggle('nav-active');
  });
}

navSlide();
nav .nav-links {
  position: absolute;
  right: 0px;
  height: 92vh;
  top: 8vh;
  background-color: #366576;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 30%;
  transform: translateX(100%);
  transition: transform 0.5s ease-in;
}

nav .nav-links li {
  opacity: 0;
}

.burger {
  display: block;
  cursor: pointer;
}


}
.nav-active {
  transform: translateX(0%);
}
<nav class="navbar">
  <div class="logo">
    <h4>Logo</h4>
  </div>
  <ul class="nav-links">
    <li>
      <a href="#header">Home</a>
    </li>
    <li>
      <a href="#about">About</a>
    </li>
    <li>
      <a href="#skills">Skills</a>
    </li>
    <li>
      <a href="#projects">Projects</a>
    </li>
    <li>
      <a href="#contact">Contact</a>
    </li>
  </ul>
  <div class="burger">
    <div class="line1"></div>
    <div class="line2"></div>
    <div class="line3"></div>
  </div>
</nav>

I've been troubleshooting this issue for more than 24 hours now without any success. Everything seems to be correctly connected, and there are no apparent errors in the code. It behaves as expected in the tutorial video I am following. Does anyone have any insights into what might be causing this problem?

Answer №1

Experiment with the media query and different screen sizes.

const navigationSlide = () => {
  const burgerIcon = document.querySelector(".burger");
  const navigationMenu = document.querySelector(".nav-links");
  const menuLinks = document.querySelectorAll(".nav-links li");

  burgerIcon.addEventListener('click', () => {
    navigationMenu.classList.toggle('nav-active');

    menuLinks.forEach((link, index) => {
      if (link.style.animation){
        link.style.animation = '';
      } else {
        link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 1.5}s`;
      }
    });

    burgerIcon.classList.toggle('toggle');
  });
}

navigationSlide();
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

nav {
    display: flex;
    justify-content: space-around;
    align-items: center;
    min-height: 8vh;
    background-color: #504954;
    font-family: 'Popins', sans-serif;
}

.logo {
    color: rgb(226, 226, 226);
    text-transform: uppercase;
    letter-spacing: 5px;
    font-size: 20px;
}

.nav-links {
    display: flex;
    justify-content: space-around;
    width: 30%;
}

.nav-links li {
    list-style: none;
}

.nav-links a {
    color: rgb(226, 226, 226);
    text-decoration: none;
    letter-spacing: 3px;
    font-weight: bold;
    font-size: 14px;
}

.burger {
    display: none;
}

.burger div {
    width: 25px;
    height: 3px;
    background-color: rgb(226, 226, 226);
    margin: 5px;
    transition: all 0.3s ease;
}

@media screen and (max-width: 768px) {
    .nav-links {
        width: 60%;
    }
}

@media screen and (max-width: 768px) {
    body {
        overflow-x: hidden;
    }

    .nav-links {
        position: absolute;
        right: 0;
        height: 92vh;
        top: 8vh;
        background-color: #504954;
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 50%;
        transform: translateX(100%);
        transition: transform 0.5s ease-in;
    }

    .nav-links li {
        opacity: 0;
    }
    .burger {
        display: block;
        cursor: pointer;
    }
}

.nav-active {
    transform: translateX(0%);
}

@keyframes navLinkFade {
    from {
        opacity: 0;
        transform: translateX(50px);
    }
    to {
        opacity: 1;
        transform: translateX(0px);
    }
}

.toggle .line1 {
    transform: rotate(-45deg) translate(-5px,6px)
}

.toggle .line2 {
    opacity: 0;
}

.toggle .line3 {
    transform: rotate(45deg) translate(-5px,6px)
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css"/>
    <title>Document</title>
</head>
<body>
    <nav class="navbar">
        <div class="logo">
          <h4>Logo</h4>
        </div>
        <ul class="nav-links">
          <li>
            <a href="#header">Home</a>
          </li>
          <li>
            <a href="#about">About</a>
          </li>
          <li>
            <a href="#skills">Skills</a>
          </li>
          <li>
            <a href="#projects">Projects</a>
          </li>
          <li>
            <a href="#contact">Contact</a>
          </li>
        </ul>
        <div class="burger">
          <div class="line1"></div>
          <div class="line2"></div>
          <div class="line3"></div>
        </div>
      </nav>

      <script src="app.js"></script>
</body>
</html>

Answer №2

It seems like the classes line1, line2, and line3 are missing, causing the "hamburger" icon to not take up any screen space for clicking. To make the .burger visible, I modified the code as below:

<div class="burger">
  <div class="line1">---</div>
  <div class="line2">...</div>
  <div class="line3">---</div>
</div>

I also included some logging:

burger.addEventListener('click', () => {
  console.log(nav.classList[1]);
  nav.classList.toggle('nav-active');
  console.log(nav.classList[1]);
});

If you click on the "hamburger" icon multiple times, the console will display alternating values of undefined and nav-active with each click.

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

The pre-existing Firebase code is experiencing functionality issues within Next.js

My current project in Next.js utilizes Firebase, but I'm encountering issues with the default code provided by Firebase. When I try to fetch inventory, it displays an error message stating "Failed to fetch inventory. Please try again." // Import the n ...

What causes the scope to shift when incorporating a Lazy function within the module pattern in JavaScript?

Implementation 1: Working code in normal var foo1 = function() { var t1 = new Date(); console.log("initialize - one time only " + this); foo1 = function() { console.log("Executes every time after initializing (initialize should not e ...

Design a captivating Profile Picture form using HTML and CSS styling

In my form, I am looking to include a user's Profile picture which should be displayed in either a circular or rectangular shape. Initially, the image area will show a black background or a placeholder image. When the user clicks on this area, they sh ...

Discovering how to create a line break within a text area using the $scope feature in Angular

I'm looking to incorporate a text area for chat input that is resizable. I would like to have some pre-filled texts in it, such as: Hi Jhon, Thanks for contacting us.... I want the text to appear on a new line after the existing content in the textar ...

The beauty of asynchronous GET requests in VueJS

As a newcomer to VueJS, I am exploring how to make a GET request to the GitHub API. Initially, I made a request to sort users by follower count, resulting in an array ordered in descending order of user logins. Following that, I sent another GET request to ...

Utilize npm to incorporate external JavaScript libraries into Meteor 1.3

Trying to integrate the OpenSeadragon library into my Meteor app has been a bit challenging. After successfully installing it via npm using meteor npm install openseadragon, I found that the OpenSeadragon docs only offer an example using the script tag. T ...

Loading jsp content into a div dynamically within the same jsp file upon clicking a link

Currently, I am working on creating a user account page. On this page, my goal is to display related JSP pages in a div on the right side when clicking links like 'search user' or 'prepare notes' on the left side. In my initial attempt ...

javascript alter css property display to either visible or hidden

I am struggling with a CSS id that hides visibility and uses display: none. The issue arises when I want the element to be visible upon clicking a button, but removing the display:none property is causing design problems due to it being an invisible elemen ...

JavaScript visibility disappearing intermittently

I have created a custom image viewer box that overlays a thumbnail gallery page. The image viewer should appear when a user clicks on a thumbnail. However, currently, the viewer only pops up briefly and then disappears again. I am looking for a way to mak ...

Is there a way to automatically fill in a MUI textfield in a React Hook form with data retrieved from Firestore?

Utilizing React Hook Forms alongside MUI TextField components has been a productive challenge for me. I've been able to successfully fetch data from Firestore and aim to prefill the form with this retrieved information. Although I am employing useFor ...

Vue JS: Easily Calculate the Total Sum of All Columns

An example of a query in the backend controller public function show($id) { $structural = DB::table('attendance')->where('payroll_daily_id',$id) ->where('assignment','STRUCTURAL') -&g ...

Stop the form from being submitted using ajax if there are no values in the form fields

Having issues with a basic form. Struggling to prevent submission when fields are empty. Is there a straightforward way to validate the fields and stop the form from submitting? Below is the HTML form: <form method="post" name="simpleForm" id="simpleF ...

Specify the controller to be used dynamically in an Angular directive

I want to be able to specify the controller that a directive uses by adding an attribute to the element - in other words, dynamically: HTML <div data-mydirective data-ctrl="DynamicController"></div> Angular angular.module('app', [ ...

Adding padding-top to the h1 element within a vertically aligned div

I have a div with a set height and the content inside adjusts vertically according to the height. To align it vertically, I added the property display-table; to the parent div and display: table-cell; vertical-align: middle; to the child div. The alignment ...

Is it possible to store Socket.IO responses in a cache for quicker retrieval?

Consider this scenario where I have a websocket implementation shown below: let itemsArray = []; function fetchData() { itemsArray = await db.query(`SELECT * FROM Items`); } function emitData() { io.sockets.in("room_foo").emit("data", JSON.stringify ...

Basics of CSS border-image explained

Although it seems simple, I'm struggling to figure out what the issue might be. I am attempting to create a div with a specific border on an ASP.Net webpage. CSS: .ResourcesDiv { border-image:url(http://blogrope.com/wp-content/uploads/2013/06/003-w ...

Executing a long job in PHP (Laravel) while simultaneously making an AJAX call

Looking to create a real-time progressing bar? I attempted to incorporate this example into my Laravel project but seem to have missed a step. Here is my HTML and JavaScript code: <div style="border:1px solid black;width:500px;height:80px"> &l ...

Tips for crafting services using $q and $http requests while avoiding redundancy

Is there an elegant way to write AngularJS services without repetitive $q syntax? I currently write services like this: (function() { function ServiceFactory($q, $timeout, $http) { return { getFoo: function() { va ...

What is the best way to have gulp monitor my sass file updates and generate a single css file?

I'm currently working on a project using ASP.NET MVC 5 framework and Visual Studio 2013. In order to automate the process of compiling my sass files and publishing them into a bundle.css file, I decided to utilize gulp. Here are the steps I took: I ...

Can HTML Elements be used within a Contenteditable section?

I am facing an issue with a contenteditable tag on my website. Users are unable to type code into the tag and have it display as an actual element instead of just text. Is there a way for users to input full, working HTML elements in a contenteditable box ...