a").on('click', function(e) { if (this.hash !== "") { e.p" /> a").on('click', function(e) { if (this.hash !== "") { e.p" /> a").on('click', function(e) { if (this.hash !== "") { e.p"/>

How can i solve Uncaught TypeError: Cannot read property 'top' of undefined

872 Views Asked by At

i have one page website. i added smoothscroll with js.

$(document).ready(function(){
    $("li > a").on('click', function(e) {
    if (this.hash !== "") {
      e.preventDefault();
      var hash = this.hash;

    $('html, body').animate({
         scrollTop: $(hash).offset().top
       }, 800, function(){
     window.location.hash = hash;
     });
    }
   });
  });

and here's my navigation html code:

<li class="{{ slug == '/' ? 'active' : '' }}"><a href="#home">HOME</a></li>
<li class="{{ slug == '/about' ? 'active' : '' }}"><a href="#about">ABOUT</a></li>
<li class="{{ slug == '/blog' ? 'active' : '' }}"><a href="#blog">BLOG</a></li>

but when i go to another page (like blog), i got error top when click the navigation to go to onepage again. did i missed something?

2

There are 2 best solutions below

3
Chaska On

Make sure you have placed related elements with a correct id in the page:

$(document).ready(function(){
    $("li > a").on('click', function(e) {
    if (this.hash !== "") {
      e.preventDefault();
      var hash = this.hash;
      if ($(hash).length > 0) {
        $('html, body').animate({
          scrollTop: $(hash).offset().top
        }, 800, function() {
          window.location.hash = hash;
        });
      }
    }
   });
  });
ul {
  position: fixed;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class=""><a href="#home">HOME</a></li>
  <li class=""><a href="#about">ABOUT</a></li>
  <li class=""><a href="#blog">BLOG</a></li>
</ul>

<div id="home" style="margin:500px 0;">
Home
</div>
<div id="about" style="margin:500px 0;">
About
</div>
<div id="blog" style="margin:500px 0;">
Blog
</div>

6
Akbar Soft On

I hope your hash will be so '#about' and '#home' '#blog' when you get them.

plaease use your hash without '#', because your id is not with "#" right?