JavaScript sticky navigation bar - error displayed in console

Hey there, I'm having an issue with my Sticky-menu. I've been trying to troubleshoot it but keep getting these console error messages: 1. Cannot read property 'offsetTop' of null at HTMLDocument. 2. Cannot read property 'classList' of null at myFunction (app.js:86) at window.onscroll (app.js:77) Can anyone help me figure out what's going wrong here?

This is the HTML code:

<header class="nav_main">
            <div class="about_nav">
                <p><a href="#b1">Lilando</a></p>
            </div>
            <div class="price_nav">
                <p><a href="#b2">Cennik</a></p>
            </div>
            <div class="lilando_nav">

            </div>
            <div class="gallery_nav">
                <p><a href="#b3">Gallery</a></p>
            </div>
            <div class="contact_nav">
                <p><a href="#b4">Kontakt</a></p>
            </div>
        </header>

Here is the CSS code:

.sticky {
position: fixed;
top: 0;
width: 100%;
    }
.nav_main {
    display: flex;
    justify-content: space-around;
    text-transform: uppercase;
    overflow: hidden;}

Lastly, this is the JavaScript code:

window.onscroll = function() {myFunction()};

    var navMain = document.querySelector("nav_main");
    var sticky = navMain.offsetTop;

    function myFunction(){
        if(window.pageYOffset >= sticky){
            navMain.classList.add("sticky")
        } else {
            navMain.classList.remove("sticky");
        }
    }

Answer №1

Obsidian Age is great for me ;)

window.onscroll = function() {myFunction()};

    var navMain = document.querySelector(".nav_main");
    var sticky = navMain.offsetTop;

    function myFunction(){
        if(window.pageYOffset >= sticky){
            navMain.classList.add("sticky")
        } else {
            navMain.classList.remove("sticky");
        }
    }
.sticky {
position: fixed;
top: 0;
width: 100%;
}
.nav_main {
    display: flex;
    justify-content: space-around;
    text-transform: uppercase;
    overflow: hidden;
}
body {
height: 1500px;
}
<header class="nav_main">
    <div class="about_nav">
        <p><a href="#b1">Lilando</a></p>
    </div>
    <div class="price_nav">
        <p><a href="#b2">Cennik</a></p>
    </div>
    <div class="lilando_nav">

    </div>
    <div class="gallery_nav">
        <p><a href="#b3">Gallery</a></p>
    </div>
    <div class="contact_nav">
        <p><a href="#b4">Kontakt</a></p>
    </div>
</header>

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 are the steps to ensure the effective functioning of my checkbox filter?

Currently, my product list is dynamically created using jQuery. I now need to implement filtering based on attributes such as color, size, and price. I found some code that filters the list items by their classes, which worked perfectly for someone else. ...

Styling of checkboxes in jQuery Mobile is missing after an AJAX request

I am currently working on implementing an ajax call to retrieve a list of items from a json array and display them as checkboxes. While the items are loading correctly, they lack the jquery mobile styling. $(document).ready(function(){ ...

Using AngularJS variables within JavaScript code

This is my introduction to using AngularJS. The code snippet below displays the desired output: <a href="http://www.example.com/xyz/{{life.animal}}/" target="_blank">Hello </a> Upon clicking, it redirects to: http://www.example.com/xyz/c ...

Vuejs - Display multiple dates within one component

I have developed various components (such as tables, selects, etc) that all rely on the same methods to access API information. The main objective is to be able to use these components across different pages of the application in a way that allows for fle ...

Tips for successfully executing queries with Axios within a Vue application

Is there a way to send query parameters using Axios so that I can access them in my backend code using req.query.email? The following approach doesn't seem to be working as expected: this.$http.post(this.$BASE_URL + 'agents/auth/create-password&a ...

Angular Commandments: Understanding the Directives

Within my code, there is a specific directive view that I am utilizing: <div class="busy-indicator angular-animate" ng-show="busy"></div> <div class="breadcrumblist" ng-class="atTopLevel ? ['at-top-level'] : null"> <div ...

What is the best way to apply changes to every class in JavaScript?

Check out this HTML and CSS code sample! body{ font-family: Verdana, Geneva, sans-serif; } .box{ width: 140px; height: 140px; background-color: red; display: none; position:relative; margin-left: auto; margin-right: auto; } .bold{ font ...

AngularJS - development of a service entity

After deliberating between posting in the Angular mailing list or seeking assistance from the JavaScript community, I have decided that this is more of a JavaScript question. Hopefully, the knowledgeable individuals on Stack Overflow can provide a quicker ...

The compatibility between Laravel's @vite('resources/js/app.js') and the froala editor plugin seems to be causing issues

I have incorporated a Vue.js based commenting system and inbox messages system in my Laravel website. Additionally, I am utilizing a wysiwyg editor (Froala Editor) in my forms for uploading projects. The issue I am facing is that the Froala Editor does no ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

What is the best method for determining the ID or class of a div element dynamically?

My issue involves a scrolling div that dynamically loads data using ajax and json from an API as you scroll horizontally. Currently, I have multiple scrolling divs on a single page. The problem arises when I need to inform jQuery about the ID of the div b ...

Using Bootstrap 4 to create a fixed-top navbar and other sticky-top elements

Check out the reproduction here: https://jsbin.com/lawafu/edit?html,output Could this be a bug, an error, a challenge, or an unattainable concept? Prior to scrolling: After scrolling: What I require: Essentially, I need the sidebar to remain visible a ...

The service worker is attempting to access outdated information from the cached script

Within my project, I implement the loading of JSON files asynchronously using import().then. At times, a situation arises where new content is accessible but has not yet been applied, causing the old cached script bundle to attempt loading the JSON files ...

Get a document from a NodeJS Server with the help of Express

How can I improve my file downloading functionality in Node.js? Currently, when I try to download a PDF file from the server, the content is displayed as data instead of initiating the download process. I would like it to function similar to how it's ...

Removing outline from a Material UI button can be done using a breakpoint

Is there a way to remove the outlined variant for small, medium, and down breakpoints? I have attempted the following approach: const selectedVariant = theme.breakpoints.down('md') ? '' : 'outlined'; <Button name="buy ...

JavaScript: Adding up whole numbers--- Reference Error: Undefined

I'm having trouble with my code because it's saying that "t1" is not defined, even though it's the name of my text box. I tried making the variable global by declaring it outside the function, but it didn't solve the issue. Interestingl ...

Having trouble hiding the message "Not found" with ng-hide and filters in AngularJS

I am currently working on incorporating instant search functionality with filters in AngularJS. My goal is to have the "Not Found!!" message displayed when the filter results in an empty array, indicating that no matches were found. However, I have encou ...

Transferring HTML variables to an Angular Component

I am currently trying to transfer the information inputted into a text-box field on my webpage to variables within the component file. These variables will then be utilized in the service file, which includes a function connected to the POST request I exec ...

Create an interactive visualization using d3.js

Currently, I am on the hunt for a technology that can help me render a tree structure based on Json data. After researching options like graphViz and d3, it seems like d3 is more optimized for modern browsers. With the extracted Json data, my goal is to c ...

Using local variables in NodeJS callbacks

Despite the abundance of information on SO, I have yet to find a suitable answer to my particular situation. The following code snippet is causing me issues: for(var i=0; i < shop.collections.length; i++){ if(!shop.collection[i].active){ var dat ...