最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot read property 'offsetTop' of null (sticky navbar) - Stack Overflow

programmeradmin1浏览0评论

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:

Uncaught TypeError: Cannot read property 'offsetTop' of null

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 5
  • Your code can't find the element with an attribute id="navbar", so the variable navbar is null – 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
Add a ment  | 

2 Answers 2

Reset to default 5

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.

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>
发布评论

评论列表(0)

  1. 暂无评论