javascript - Cannot read property 'offsetTop' of null - Stack Overflow

Hi I have problem with my code. I am trying to do simple scroll function, but i still received an error

Hi I have problem with my code. I am trying to do simple scroll function, but i still received an error.

    <script>
    function pageScroll(el) {
    var yPos;
    page = document.getElementById(el);
    var height = page.offsetTop;

    window.scroll(0, height);
    }
</script>

<button class="module-box" onclick="pageScroll(about)">READ</button>

Hi I have problem with my code. I am trying to do simple scroll function, but i still received an error.

    <script>
    function pageScroll(el) {
    var yPos;
    page = document.getElementById(el);
    var height = page.offsetTop;

    window.scroll(0, height);
    }
</script>

<button class="module-box" onclick="pageScroll(about)">READ</button>
Share Improve this question asked May 26, 2016 at 9:46 matimati 971 gold badge3 silver badges11 bronze badges 5
  • This means page doesn't store what you think it does. – Mitya Commented May 26, 2016 at 9:47
  • 1 Try sending the argument as a string - instead of pageScroll(about) try using pageScroll('about'). This should do the trick. – Leo Napoleon Commented May 26, 2016 at 9:49
  • I suppose that the problem lies in the variable page, but you can explain to me what I'm doing wrong? – mati Commented May 26, 2016 at 9:50
  • @LeoNapoleon THANKS! – mati Commented May 26, 2016 at 9:51
  • about should be a string to be able call getElementById so replace pageScroll(about) with pageScroll('about') – Vladu Ionut Commented May 26, 2016 at 9:51
Add a ment  | 

1 Answer 1

Reset to default 2

Working code. Need to pass id as string to the function.

function showTop(el)
{
  var page = document.getElementById(el);
    var height = page.offsetTop;
  alert(height);
  }
<div id="new"></div>
<button onclick = "showTop('new')">Click me</button>
  <div id='op'></div>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742340739a4425576.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信