Issue: Switching between concealing and revealing is not functional

body {
    margin: 0;
}
a{
    text-decoration: none; 
    color: lightseagreen;
}
a:hover {
    color: lightgray;
}
/* full bar*/
.navbar {
    display: flex;
    justify-content:  space-between;
    align-items: center;
    background-color: white;
    padding:  9px 12px;
}
/* Menu*/
.navbar_menu {
    display: flex;
    list-style:none;
    padding-left:0;
    font-size: 33px;
    font-family: initial;
}

.navbar_menu li {
    padding: 8px 30px;  
    display: inline;
}

.navbar_icons {

    letter-spacing:30px;
    list-style: none;
    display: flex;
    flex-direction: row;
    width: 200px;
    color: lightgray;
    font-size: 2em;
    padding-left:0;

}
/* Icons */
.navbar__icons li {
    padding: 8px 12px;
    display: none;
  }
/* Toggle button */
.navbar_toogleBtn{
    position: absolute;
    /*only appears when the screen is small*/
    display: none;
    right: 32px;
    font-size: 24px;
}

/*For small screen */
@media screen and (max-width: 768px){
      /* Nav container */
    .navbar{
        flex-direction: column;
        align-items: center;
        padding: 8px 24px;
    }
 
      /* Menu */
    .navbar_menu{
        display: none;
        flex-direction: column;
        align-items: center;
        padding: 5px 10px;
        justify-content: center;

    }
   .navbar_menu li{
       width: 100%;
       text-align: center;
       display: block;    
   }

   .navbar__menu a {
    /* Fill in an entire line so that user can click on any space */
    display: block;
    
  }

   /* Icons */
    .navbar_icons {
        justify-content: center;
        display: none;
        flex-direction: row;
        width: 100%;
        font-size: 1.5em;
        
    }
      /* Toggle button */
    .navbar_toogleBtn{
        display: block;
    }
    /* When toggle button is clicked - active state */
    .navbar_menu.active,
    .navbar_icons.active {
        display: flex;
    }
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="bar.css" />
    <title>first page</title>
    <script src="https://kit.fontawesome.com/265fcd9b69.js" crossorigin="anonymous"></script>
    
</head>

<body>
    <nav class="navbar">

        <div class="navbar_logo">
            <img src="logo.png" width="300" height="200">

        </div>
      <!-- Menu -->
        <ul class="navbar_menu">
            <!-- info.html, partner.html, free.html are random placeholders -->
            <li><a href="">Home</a></li>
            <li><a href="Info.html">Information</a></li>
            <li><a href="Partner.html">Partner</a></li>
            <li><a href="Free.html">Freelancer</a></li>
            <li><a href="Comunity.html">Community</a></li>
        </ul>

        <!-- Icons -->
        <ul class="navbar_icons">
            <li><a href="login.html"><i class="fas fa-sign-in-alt"></i></li>
            <li><a href="register.html"><i class="far fa-registered"></i></li>
        </ul>

        <!-- Toggle button -->
        <a href="#" class="navbar_toogleBtn">
            <i class="fas fa-bars"> </i>
        </a>

    </nav>
    <script type="text/javascript"  src="bar.js" charset="utf-8" defer></script>
</body>

</html>
const toggleBtn = document.querySelector('.navbar__toggleBtn');
const menu = document.querySelector('.navbar__menu');
const icons = document.querySelector('.navbar__icons');

toggleBtn.addEventListener('click', () => {
  menu.classList.toggle('active');
  icons.classList.toggle('active');
});

I am currently following a YouTube tutorial to learn HTML/CSS/JS. I'm trying to write JS code but I'm encountering a problem that I can't seem to solve. I hope someone can provide me with a solution.

The issue revolves around add.EventListener. When I check the code in Chrome, the console displays:

"bar.js:5 Uncaught TypeError: Cannot read property 'addEventListener' of null"

I want to implement a toggle function to hide and show elements with JS.

Answer №1

The reason for the error message ( "bar.js:5 Uncaught TypeError: Cannot read property 'addEventListener' of null" ) is due to incorrect element classes being specified in the javascript code.

You should update your code as follows:

const toggleBtn = document.querySelector('.menu_toggleBtn');
const navMenu = document.querySelector('.navigation_menu');
const socialIcons = document.querySelector('.social_media_icons');

This correction aligns with your HTML elements:

<a href="#" class="menu_toggleBtn">
...
<ul class="navigation_menu">
...
<ul class="social_media_icons">

Answer №2

It's difficult to pinpoint the exact issue without reviewing your code. Null signifies the absence of a value or object. When attempting to access a selector that doesn't exist, you may encounter a null error. Double-check that you are targeting the right element by verifying its ID or class.

Compare your code with the following example to identify any potential oversights. This is a fundamental illustration.

var box = document.getElementById('box');

document.getElementById('button').addEventListener('click', function(){
    if( box.classList.contains('active') ){
    box.classList.remove('active'); 
  } else {
    box.classList.add('active') ;
  }
});
#button {
  background-color: orange;
  border: 1px solid #000;
  color: #000;
  padding: 0.5rem 1rem;
  cursor: pointer;
}
#box {
  margin-top: 2rem;
  display: none;
  padding: 1rem;
  border: 1px solid #000;
}
#box.active {
  display: block;
}
<button id="button">CLICK ME</button>
<div id="box">I am a box. Watch me.</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

Leveraging shadow components with the Next.js pages directory

I am facing an issue with getting a simple shadcn button to work because I am unable to import the button. Although I am using nextjs 13, I am still utilizing the pages directory. Below is the process of how I installed shadcn. Here is the installation co ...

Are asynchronous promises thenable for chaining?

Can someone explain to me how asynchronous chaining works with thenable? I am new to using promises in Node.js and I am a bit confused about the concept. In the code example provided below, it seems like the promise returned from the previous Promise.the ...

unable to modify the content of a

I need assistance with a javascript function that dynamically creates panels using an ajax request. Once the request returns valid json data, I populate all the widgets as follows: function createAllWidgets() { var funcid = 'get_widget_info' ...

HTML textarea content will update automatically whenever there is an input change in JavaScript

Everything seems to be working as expected, but I noticed that the onmouseover event only triggers once. Is there a way to make it work multiple times, i.e., every time the text array changes? <html> <head> <script> function myFunct ...

Is it possible to connect to a Node server from outside the network if the application is only listening on 'localhost'?

When utilizing the Express framework and we implement app.listen(port), the app will be located at localhost:port/ On a local machine, it is clear how to access this address using a local browser running on the same machine. Even clients within the same n ...

"Implement a feature to recognize and handle various file extensions within an npm

I need help with my npm script where I am trying to include both ts and tsx file extensions. My current code snippet is as follows: "test": "mocha ..... app/test/**/*.spec.{ts,tsx}" Unfortunately, the above syntax is not working correctly. Can someone pl ...

Analyzing two disorganized sets in MongoDB

I need to compare a large number of documents stored in two collections. In total, there are approximately 1300 documents in each of these collections. My goal is to create a diff comparison report after comparing the two collections. My main focus is on ...

Identify the completion of all JQuery, JavaScript, and Ajax requests

Is there a way to inject a script into a page that can determine if any scripts are still running, Ajax calls are in progress, or the page is not fully loaded? This is important for checking the existence of various elements using JQuery and performing act ...

Alert the host about any updates

I am currently working on an ASP.NET application that is hosted by a C# application using WebBrowser. The ASP.NET application runs within the C# application environment. My challenge lies in finding a way to notify the C# application when certain events, ...

While attempting to deploy my project on Vercel by pulling in my code from GitHub, I ran into this error

As a self-taught Front End developer diving into building and hosting my first web page using React, I've encountered this warning. Any suggestions on how to resolve it? Cloning gitohub.com/Passion94/React-Apps (Branch: main, Commit: da89a2a) Cloning ...

Is there a way to configure a Mui textfield to only allow numeric input? It currently accepts numbers, the letter "e," and dashes

Take a look at my current code. <TextField error={values[1].error} fullWidth id="id" type="number" value={values[1].Id} placeholder='Enter ID' onChange={handleChange(1,'Id')} variant="outlined" inputProps={{min: 0,inputMode: &apos ...

Is there any purpose to incorporating an AngularJS directive within a comment?

Hello, I'm curious about the purpose of using an AngularJS directive as a comment. I've seen some examples where it can display an alert message, even with arguments, but I'm struggling to see the practical use of a directive as a comment. C ...

Attaching a JavaScript-infused text to innerHTML within a template

In a Windows 8 metro style app, I am working with a list of articles that are passed to a Flip View Control. Each article contains a description text in HTML which includes JavaScript. I understand the need to use the `MSApp.execUnsafeLocalFunction` functi ...

Client connected via Socket.io is not receiving the message event

My project was built using express-generator as the skeleton, so I had to implement a workaround which I found here. SERVER: io.on('connection', function(socket){ socket.on('message', function(msg){ io.emit('message', msg) ...

JavaScript conditional calculation mechanism

Here is the code snippet I am referring to: function myFunction() { var x = document.getElementById("ins-feet").value; if(x >= 0 && x <= 1499) { document.getElementById("show-cost").innerHTML = "Cost: $" + 300; } else if ...

Having trouble with updating PHP MySQL data using serializeArray?

My HTML page includes a display of temperature with two buttons - one for updating MySQL with the temperature setting and the other for toggling on/off data. Previously, everything was functioning correctly with the initial code: function myFunction() { ...

What is the process for activating a button after a checkbox has been selected? Additionally, how can a value be dynamically transferred from a checkbox to the rezBlock_1 block?

What could be the reason for my code not functioning properly? How can I enable a button once a checkbox is selected? Also, is there a way to dynamically move text from a checkbox to the rezBlock_1 block? CODPEN https://codepen.io/RJDio/pen/RwPgaaZ doc ...

Display the quantity of stock in WooCommerce as separate numerical values

I am looking to display the stock quantity of products on a specific page of my website. The code I am currently using to retrieve the stock quantity is as follows: <p class="stock-m13"><?php echo $product->get_stock_quantity(); ?></p> ...

Accessing data from a live database in a randomized sequence

When retrieving items from a database, there is often a common code pattern that looks like this: const [dataRcdArray, setDataRcdArray] = useState<never[]>([]); ..... snapshot.forEach((child:IteratedDataSnapshot) => { setDataRcdArray(arr ...

What steps can be taken to hide empty items in a list from being shown?

When I map over an array of books to display the titles in a list, I encounter an issue with the initial empty string value for the title. This causes the list to render an empty item initially. Below is my book array: @observable books = [ {title:" ...