The hamburger menu functions properly on the homepage but is not working on the individual about page

The burger menu was causing issues initially due to a simple spelling mistake, which I only noticed later. However, the current issue seems more complex. I am now creating separate pages for different sections of my website, such as About Me, Education, etc. The About Me page is the only one I have started working on so far. While the burger menu functions correctly on the Home page, it does not work on the About page. I have organized each file within its own folder to maintain a tidy structure.

/* ----SCROLL SECTION ACTIVE LINK---- */
let sections = document.querySelectorAll('section');
let navLinks = document.querySelectorAll('header nav a');

window.onscroll = () => {
  sections.forEach(sec => {
    let top = window.scrollY;
    let offset = sec.offsetTop - 150;
    let height = sec.offsetHeight;
    let id = sec.getAttribute('id');

    if (top >= offset && top < offset + height) {
      navLinks.forEach(links => {
        links.classList.remove('active');
        document.querySelector('header nav a[href*=' + id + ']').classList.add('active');
      });
    };
  });
  /* ----STICKY NAVBAR---- */
  let header = document.querySelector('header');

  header.classList.toggle('sticky', window.scrollY > 100);

  /* ----REMOVE TOGGLE ICON AND NAVBAR WHEN CLICK NAVBAR LINK (SCROLL)---- */
  menuIcon.classList.remove('bx-x');
  navbar.classList.remove('active');
};

// Rest of the JavaScript code goes here...

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&display=swap');
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  text-decoration: none;
  border: none;
  outline: none;
  scroll-behavior: smooth;
  font-family: 'Poppins', sans-serif;
}

// Rest of the CSS code goes here...

About Me Page

<!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">
        <title>About Me</title>

        <!-- ----BOX ICONS---- -->
        <link href='https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed8f8295848e82839eaddfc3dcc3d9">[email protected]</a>/css/boxicons.min.css' rel='stylesheet'>


        <!-- ----CUSTOM CSS---- -->
        <link rel="stylesheet" href="../css/style.css">

    // Rest of the HTML markup and CSS code specific to the About Me page goes here...

Answer №1

After attempting to replicate the mentioned issue, I encountered an error message related to the menuIcon element:

Uncaught ReferenceError: Cannot access 'menuIcon' before initialization at window.onscroll (main.js:25:3)

This error signifies that an effort is being made to access the variable menuIcon before it is properly initialized. In the provided code snippet, menuIcon is initialized by utilizing

document.querySelector('#menu-icon');
to locate an element in the HTML document with the ID of "menu-icon" and assign it to the menuIcon variable. However, the error-triggering code is situated within the window.onscroll function which executes whenever a user scrolls the page. It is intended to toggle the bx-x class on menuIcon when the user clicks on it. Since the menuIcon variable has not been initialized when the window.onscroll function is executed, the aforementioned error is thrown.

To resolve this issue, it is suggested to relocate the initialization of the menuIcon variable to the beginning of the JavaScript file, preceding the window.onscroll function. By doing so, the variable will be accessible and usable throughout the file.

/* ----SCROLL SECTION ACTIVE LINK---- */
...
/* ----TOGGLE ICON NAVBAR---- */
let menuIcon = document.querySelector('#menu-icon');
let navbar = document.querySelector('.navbar');

menuIcon.onclick = () => {
  menuIcon.classList.toggle('bx-x');
  navbar.classList.toggle('active');
};
window.onscroll = () => {
 ...
};

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 achieve transparency for an element while it is nested within multiple parent

Is there a clever method to achieve transparency for an element that allows the background of its parent element to shine through and display the body background, for example? Consider this scenario: <body style="background: url(space.jpg)"> <di ...

Performing a modulo operation within a v-for loop

I'm showcasing divs in a loop and I need to assign classes based on the loop index. My goal is to have index 0 and 1 with the class col-6, then indexes 2,3,4 with the class col-4, followed by index 5 and 6 having the class col-6, and so forth. This w ...

verification tool for a less file's syntax

Searching for a tool to validate a specific less file at the syntax level. The issue lies in the validator not recognizing dependencies or detecting declared mixins. Many existing less processors do not work due to missing dependencies that cannot be prov ...

Is it possible to use the .map() method on an array with only 3 items and add 2 additional placeholders?

I need to iterate through an array of 5 items in a specific way: list.slice(0, 5).map((i) => { return <div>{i}</div> }); However, if the array only contains 3 items, I would like to add placeholders for the remaining 2 items in my reac ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

The image showcases interactive hover effects that resemble a button popping up

Welcome to my HTML code showcase: <div class="container"> <a target="_self" href="flower_gallery.htm"> <img data-src="holder.js/180x180" style="height:20%;width:100%;float:left;" ...

Vue - the <script setup> element is unable to execute scripts

I have a functional widget from Atlassian that works as expected when used in an HTML file: <html lang="en"> <head> <script data-jsd-embedded data-key=<key> data-base-url=https://jsd-widget.atlassian.com src=https://jsd-w ...

Troubleshoot: Problem with iPhone Orientation on Bootstrap Framework

While working on a responsive website design, I encountered an issue that needs addressing. Initially, switching from portrait mode to landscape didn't trigger the expected responsive behavior; instead, it simply zoomed into the site. To prevent this ...

Enzyme's simulate() failing to produce expected results with onChange event

I am facing an issue with a component and its related tests: import React from 'react'; import PropTypes from 'prop-types'; function SubList (props) { var subways = ['', '1', '2', '3', & ...

Unable to save array in global variable using Ajax, constantly receiving undefined

I'm attempting to store an array obtained from an ajax call in a global variable so that I can access it later, but I keep encountering an undefined error. <script> var items = []; function add(value){ items.push(value); ...

Issue with JQuery Each function not waiting for the inner function to complete

When I have this section inside an ajax function $.each(data['Result'][0], function(Key, Value) { InputGen(Value['Type'], Value['Name'], Value['Other'], Value['Value'], function(Html){ Table = ...

Add an arrow or triangle at the tip of the line

I am currently working on recreating the design of lines with an arrow or triangle at the end side of an Input form. The inspiration for this comes from an old flash application that is now being converted to HTML5: https://i.sstatic.net/OCpif.jpg So far, ...

"Utilizing jQuery Autocomplete with an external data source and interactive row additions

I have come up with a plan: When the user types in the search textbox, it will show autocomplete suggestions and display the result on textbox 1, textbox 2, textbox 3. The user can then enter the desired Quantity in textbox 4. After finding an item and ...

Is it possible to perform a GET request between a site using HTTPS and another using HTTP?

https://i.stack.imgur.com/AlWYJ.png I recently hosted my site on Shopify using HTTPS, and then I attempted to make a GET request via Angular to a site that uses HTTP. Angular <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.j ...

What is the proper way to place a newly added element using absolute positioning?

Currently, I am in the process of developing a tooltip feature. This function involves adding a div with tooltip text inside it to the element that is clicked. However, I am facing a challenge in positioning this element above the clicked element every tim ...

What is the best way to align text in the center of a button?

When creating custom buttons in CSS using <button>, I noticed that the text appears to be centered both horizontally and vertically across all browsers without the need for padding, text-align, or other properties. Simply adjusting the width and heig ...

Adjustable textarea with automatic height based on content and line breaks

Imagine you have a textarea with text that includes line breaks. If you style it like this: textarea { height: auto; overflow: hidden; resize: none; } Upon loading the page, the textarea will only adjust its height based on the content until it enc ...

Tips for concealing a div when clicking on an element solely with CSS

I am currently working on creating a CSS Main Menu in Vue. The functionality is such that it pops up when the mouse hovers over it, and hides when the mouse moves out. However, I am facing an issue with hiding the menu when clicking on a hyperlink a. Any s ...

Do [(ngModel)] bindings strictly adhere to being strings?

Imagine a scenario where you have a radiobutton HTML element within an angular application, <div class="radio"> <label> <input type="radio" name="approvedeny" value="true" [(ngModel)]=_approvedOrDenied> Approve < ...

Analyzing User Input and Database Information with Mongodb

Here's the HTML form I'm working with: <form id="contact-form" method="POST" action="/search"> <label for="company">Phone company</label> <input type="text" name="company" value=""> &l ...