1

JS CODE:

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

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

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

What's wrong with this? I found a w3school example of sticky navigation. In the console it displays:

Uncaught TypeError: Cannot read property 'offsetTop' of null

omikes
  • 6,140
  • 8
  • 33
  • 44
Mark
  • 176
  • 2
  • 13

2 Answers2

4

It looks like it can't find any element with the id "navbar".

This could be caused by not having an element with the id "navbar".

Alternatively, if you do have an element called "navbar", this code is likely running before the page has finished loading. The easiest way to fix this is to put the javascript at the bottom of your page. Alternatively, you can use jQuery's $(document).ready, or one of the vanilla alternatives from this question.

Nicholas
  • 3,643
  • 2
  • 7
  • 17
0

Besause your demo has not a element named 'navbar'

You should create a tag like this div in your HTML code

 <div id='navbar'></div>