Issue with the responsive navigation bar on the website

I've created a script for a toggle button in the navigation bar. When clicked once, it should open the menu, and when clicked again, it should close it.

However, I'm facing an issue with this script.

Here's the Script:

const navSlide = () => {
  const togg = document.querySelector('.toggle');
  const navs = document.querySelector('nav-links');

  togg.addEventListener('click', () => {
    navs.classList.toggle('nav_ul_active');
  });
}

Related HTML Code:

<div class="toggle" onclick="navSlide()">
  <div class="menu"> <i class="fa fa-bars" aria-hidden="true"></i> </div>
</div>
<div class="nav-links">
  <ul class="nav_ul">
    <li><a href="#head-proj">Projects</a></li>
    <li><a href="#head-about">About</a></li>
  </ul>
</div>

Upon refreshing my website and clicking the button, I encounter the following error:

Uncaught TypeError: Cannot read property 'classList' of null at HTMLDivElement. (app.js:6)

The file 'app.js' is where the error occurs. How can I resolve this issue?

Answer №1

querySelector() requires a CSS selector string. Remember to use a dot for classes:

document.querySelector('.nav-links')

For more information on how to use class selectors, check out Class selectors.

Additionally, avoid binding click handlers within click handlers as this can result in multiple bindings and unexpected behavior. It's recommended to remove the inline onclick attribute and utilize addEventListener instead.

const togg = document.querySelector('.toggle');
const navs = document.querySelector('.nav-links');

togg.addEventListener('click', () => {
  navs.classList.toggle('nav_ul_active');
});
.nav_ul_active {
  background-color: red;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>

<div class="toggle">
  <div class="menu"><i class="fa fa-bars" aria-hidden="true"></i></div>
</div>
<div class="nav-links">
  <ul class="nav_ul">
    <li><a href="#head-proj">Projects</a></li>
    <li><a href="#head-about">About</a></li>
  </ul>
</div>

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 datatable does not adjust to changes in page size

My jsfiddle example showcases different card boxes, and I am currently focusing on making the 'Table 1' box responsive. However, I have encountered an issue: Check out my jsfiddle example here code If you open the jsfiddle with a large enough ...

Is there a way to trigger a method in the controller using ajax from the view?

As I create a survey, each question has its own partial view and the entire survey is displayed using pagination. You can see how this works in the image below: https://i.sstatic.net/Dqx0w.png Users can submit their answers to the server by utilizing the ...

ESLint flagging "Unexpected tab character" error with "tab" indentation rule enabled

Currently, my ESLint setup includes the Airbnb plugin (eslint-config-airbnb) along with the Babel parser. I recently decided to enforce the rule of using Tab characters for indentation instead of spaces. This is how my .eslintrc file looks like: { "p ...

What is the best way to handle an array (or manually loop through ng-repeat)?

AngularJS Version: 1.3.15 Confession: While I have limited knowledge of AngularJS, I am required to utilize it due to its integration in the framework I am working with. I aim to make changes to some HTML/AngularJS code that currently appears as follows: ...

The art of slipping away from a character in JavaScript while adding HTML using jQuery

I am trying to add multiple HTML canvas elements to an existing HTML canvas. <div> <canvas id="BackGroundImage" width="800" height="300" style="position: absolute; z-index: 0;"></canvas> <canvas id="canvas" width= ...

Initiate a jQuery function once the document is fully loaded

Is there a way to apply the Javascript code within my .change() function to the same function in the .ready() function without duplicating the code? $('.selabw').change(function(){ let that = $(this); let value = that.parent().next(). ...

Angular directive dilemma

Angular is causing some issues for me as I am a beginner in using it. Below is the JSON data that I am dealing with: [ { "name":"43", "values":{ "audio":"Audio Only", "low":"Low Bandwidth", "medium":"Medium Bandw ...

Creating Form Elements Dynamically: A Step-by-Step Guide

How can I create a dynamic form based on the number of rows entered by the user? I've been struggling with this issue for over an hour, trying different approaches in PHP and now considering using Javascript. If you have any tips or suggestions, ple ...

Update a div container using jQuery

Hey there, I need some help with a specific part of my code snippet: <div class="tags-column" id="tags"> <h2>Tags</h2> <ul> <% @presenter.tag_counters.each do |tag_counter| %> <li class=" ...

When accessing `document.getElementById()` from an external JavaScript file, it may sometimes return a value

On my aspx page, I am calling the 123.js file from within the solution. Here is how it looks: <%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="1.aspx.cs" Inherits="1" ValidateRequest="false"%> & ...

Is the line-height percentage relative to the viewport or the font size?

Can anyone help me understand the line-height property better? How does it work when set in %? When using: line-height: normal; line-height: 1.6; line-height: 80%; What is the percentage relative to? ...

Techniques for adding multiple elements in a grid system while ensuring responsiveness

Looking for guidance on designing a responsive screen using the Bootstrap-4 grid system for web development. Here's an image of what I'm aiming to create using rows and columns: View the grid picture here Code snippet: <div className="row"& ...

Obtain the URL value using jQuery and place it inside a <span> element

How can I insert a href value into the span tag like this? <p class="name"> <a download="adja-lo.pdf" title="adja-lo.pdf" href="http://localhost/MatrixDRSnews/apps/Matrix/server/php/files/adja-lo.pdf">adja-lo.pdf</a> </p> ...

Error: react/js encountered an unexpected token

While attempting to execute my project, I encountered an error in the console related to a function within the code. The exact error message reads as follows: "63:25 error Parsing error: Unexpected token, expected (function toggleDrawer = (open) => () ...

How can Flot charts be configured to display only one tick per month on the x-axis?

Is there a way to ensure that there is exactly one tick on the x-axis every month when using Flot charts? I have set the minTickSize to [1, "month"] but sometimes it only plots 1 tick in the x-axis every 2 months var options = { xaxis: { mode: "time ...

Invoking a parent method in ReactJS through two layers of components using TypeScript

I'm facing an issue while trying to call a method from a parent component that is two layers above. Whenever I attempt to do so, nothing happens or I get an error saying that the function is not defined. Here is my Child Component: class Child extends ...

Create a responsive iframe that expands to fullscreen when a button is clicked

Currently, I am using the following code to create an adaptive iframe with a fixed ratio for both width and height: <div id="game-container" style="overflow: hidden; position: relative; padding-top: 60%"> <iframe style="position: absolute; width ...

Is there a similar function to -moz-linear-gradient in Chrome?

My button's CSS includes background: -moz-linear-gradient(center top, #59a1d8, #27247D) repeat scroll 0 0 #0f78c7;, which works well in Mozilla Firefox. However, it does not display properly in the Chrome browser. Can someone suggest an equivalent cod ...

recording the "mouseenter" event when the mouse enters the element from within

For an interesting visual representation, check out this fiddle Don't worry about the CSS for now. The main objective of this block of jQuery code is to determine the direction opposite to where the mouse initially entered into the .container elemen ...

Is it possible to add items to a JS object that isn't an array?

Here is an example of the object I am working with: { "_id": "DEADBEEF", "_rev": "2-FEEDME", "name": "Jimmy Strawson", "link": "placeholder.txt", "entries": { "Foo": 0 } } To access this data in my JavaScript code, I use a $.getJSON call. ...