styles.css is generating an ERROR message, indicating that it is unable to read properties of null when trying to access the 'classList'

Hey there, I've been working on adding a background color change to my navbar when the scrollY exceeds 30px, and it's functioning properly. However, I'm encountering an error in the console which states that the new classList cannot be added to the header once it surpasses 30px.

This is how my .ts file looks like:

ngOnInit(): void {   
    function scrollHeader(){
      const nav = document.getElementById('header');
      if(window.scrollY >= 30){ 
        nav.classList.add('scroll-header');
      }else{
        nav.classList.remove('scroll-header');
      }
    }
    window.addEventListener('scroll', scrollHeader);
}

Here is the styling in my style sheet:

.scroll-header{
    background: #242526;
    color: white;
}

.scroll-header .wrapper .logo a{
    color:white;
}

And this is the content of my HTML File:

<nav id="header">
    <div class="wrapper">
        <div class="logo">
            <a [routerLink]="'/'">InsuranceBazaar</a>
        </div>
        <input type="radio" name="slider" id="menu-btn">
        <input type="radio" name="slider" id="close-btn">

        <ul class="nav-links">
            <label for="close-btn" class="btn close-btn">
                <i class="fa fa-times"></i>
            </label>
            
            <li>
....

If you have any insights on how to resolve this issue possibly related to ngOnInit(), please share them with me. Your help would be greatly appreciated!

Answer №1

Have you verified the accuracy of your function call?

You might want to consider removing the use of ngOnInit().

Additionally, have you attempted monitoring the scroll behavior using console.log()? Alternatively, experimenting with a more targeted approach such as #header.scroll-header could help refine your styling...

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

What is the best way to retrieve information from a data set?

After borrowing some basic HTML, CSS, and JavaScript code from CodePen, I ran into an issue while attempting to convert it to React. The error message says that it cannot read properties of null (specifically 'dataset'). Here is the JavaScript c ...

Angular Material throws errors when there are missing dependencies

I encountered an issue while trying to set up angular material in my project: Uncaught TypeError: Object(...) is not a function at bidi.es5.js:87 at Object../node_modules/@angular/cdk/esm5/bidi.es5.js (bidi.es5.js:89) at webpack_requir ...

Unexpected patterns observed when utilizing parent/child routing files

I am working with a Node/Express backend that is implemented using TypeScript. Whenever I make changes to a file and save it, if I test the root route in Postman localhost:8000/, I receive the expected response. However, when I test localhost:8000/user af ...

Is it possible to create a webpage that is invisible to users accessing it from a desktop device

Is it possible to create a webpage that is only visible on tablet and mobile devices, while redirecting desktop users somewhere else? I want this page to be hidden from desktop users entirely. ...

Presentation with multi-directional animations

Curious to know if it's possible to create a unique slideshow that scrolls in multiple directions? The concept is to display various projects when scrolling up and down, and different images within each project when scrolling left and right. Is this i ...

Using an AngularJS directive that has a dynamic ID may cause issues with d3's ability to append

I encountered a situation where my angularJS directive works fine when I specify a hardcoded ID for appending elements, but fails to append when the ID is dynamically generated. Surprisingly, there are no errors reported by d3 or the browser. However, upon ...

Stop the container from wrapping and allow its children to wrap instead

Here is a snapshot of my current layout: <div class="left"> ... </div> <div class="right"> <div class="inner" /> ... several more of these ... <div class="inner" /> </div> My CSS code looks like this: ...

Finding the nth-level children using JQuery

Is there a way to select nth-level children in CSS/jQuery without using any ID or class references, only tag names? I know how to get first level children with the selector div#block > div. But I am looking for a solution to target deeper levels. & ...

How can I utilize the color prop in the theme file to style new variants more comprehensively with MUI theming?

I am working on creating a custom variant for an MUI button where the color specified in the color prop should be applied as both the border and text color. While the MUI documentation offers a suggested approach, it requires addressing each available col ...

Displaying an HTML button above JavaScript code

Hello, I am currently working on a project that involves displaying the Earth and I am in need of assistance with positioning some buttons on the screen. Currently, I am facing an issue where the buttons appear either above or below the JavaScript code. I ...

Making use of CSS to manipulate the placement of images within a grid

I've been struggling to insert an image into a grid, and it's causing some issues for me. Currently, the main problem I'm facing is that it's pushing another grid item down. body { padding: 0; margin: 0; } .main { wi ...

Switching positions in Azure DevOps (Angular + API): How can the Angular configuration be modified for the designated slot?

Setting up the Angular app can be quite tricky. In our Azure Yaml pipeline publishing job, we tackle the challenge by executing a "token" replacement to tailor the configuration for the specific target environment within a tokenized artifact. Subsequently ...

When submitting forms in AngularJS, make sure to include empty fields as null values instead of excluding them entirely

Check out my HTML / Angular code below: <form ng-submit="ctrl.add()"> <div class="form-group"> <label>Username</label> <input type="text" ng-model="ctrl.user.username"> </div> <div class ...

Symbols in the URL undergo hexadecimal conversion while the page is loading

Whenever I click on a link, the URL changes abruptly during the page loading process. For example, when I click on a link like www.test.com/main#/?arg1=1&arg2=2, it initially appears in the URL bar. However, as the page loads, the URL suddenly transfo ...

Effortless JSON parsing with Angular 2 Http GET request

After sending an HTTP get request to my server API, I am attempting to parse the JSON object that is returned. Below is the code snippet for the Http call: getPayoutReport(param1, param2, param3) { //perform necessary actions //set up a requestUr ...

What steps can be followed to incorporate a loading gif into this popup and subsequently eliminate it?

These simple inquiries are starting to get on my nerves. I can't keep waiting around for my website designer to resolve this issue. It shouldn't be that difficult... I managed to figure out most of it by researching similar questions, but I could ...

Tips for injecting Angular service for login in Cypress tests

Recently, I decided to incorporate Cypress into my testing process for my Angular application. Following Cypress's recommendation, I aimed to streamline testing by skipping the login screen and directly accessing my Angular LoginService. To guide me ...

Misalignment of Font-awesome icons in the footer section

I've implemented a footer on my website. My goal is to have the icons centered both vertically and horizontally, with the colored area: Always positioned at the bottom of the screen No taller than the icons themselves Here's the code snippet: ...

Skip a single test from a suite in Firefox using Protractor automation framework

I have a collection of tests in my tests folder, all named with the convention ending in spec.js. By using the */spec.js option in the Config file, I am able to run all tests seamlessly. However, I encountered an issue where I needed to skip running a spe ...

Having issues with the functionality of Bootstrap 4 popover?

In my Spring MVC web project, a Bootstrap popover appears when the help icon is clicked. However, on the first click, the popover opens and moves away from the icon. After closing it and clicking again, the popover correctly positions itself. When I chan ...