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
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:
Share Improve this question edited Mar 8, 2019 at 21:45 omikes 8,5619 gold badges38 silver badges52 bronze badges asked Mar 8, 2019 at 20:45 MarkMark 2161 gold badge4 silver badges13 bronze badges 5Uncaught TypeError: Cannot read property 'offsetTop' of null
-
Your code can't find the element with an attribute
id="navbar"
, so the variablenavbar
isnull
– Get Off My Lawn Commented Mar 8, 2019 at 20:46 - Sorry, wrong code, check again ! – Mark Commented Mar 8, 2019 at 20:48
- How to fix it, example please! – Mark Commented Mar 8, 2019 at 20:49
- You need to execute that code after the html has been generated. – Get Off My Lawn Commented Mar 8, 2019 at 20:50
- Possible duplicate of Why does jQuery or a DOM method such as getElementById not find the element? – Get Off My Lawn Commented Mar 8, 2019 at 20:54
2 Answers
Reset to default 5It 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.
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>