1

I am trying to get a slow scroll effect when a button is clicked. Now i found a function to jump to a hash of the page when an element is clicked.

I use the scrolltop method to jump down my page. I go -220 down the page.

Error message in the browser:

Uncaught TypeError: Cannot read property 'top' of undefined
at HTMLDivElement.<anonymous> (script.js:35)
at HTMLDivElement.dispatch (jquery.min.js:2)
at HTMLDivElement.y.handle (jquery.min.js:2)

Any help is welcome . If you have question please ask.

Code:

$(document).ready(function() {
  $("#choose-time div").on('click', function(event) {
    $(this).toggleClass("selectedBox");

    if (this.hash !== '') {
      event.preventDefault();
      var hash = this.hash;

      $("html, body").animate({
        scrollTop: $(hash).offset().top - 220
      }, 900);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="choose-time">
  <h2>Kies een Datum</h2>
  <div>
    <p>Donderdag</p>
    <p>28/04/2019</p>
  </div>
  <p><strong>Click</strong> de gewenste datum aan a.u.b</p>
</section>
Pete
  • 57,112
  • 28
  • 117
  • 166
Sebastian
  • 23
  • 5
  • You got error because of 'this.hash' is undefined and hence it got undefined in 'hash' variable. – Nick Mar 26 '19 at 12:55

2 Answers2

0

I think you need to correct hash you used. Check below link to see how hash works in jQuery. How does $(this.hash) work?

Second option, you can use specific ID or Class and increase time

    $("html, body").animate({
      scrollTop: $("#elementId").offset().top - 220
    }, 4000);
0

You can use below code as your jQuery

$(document).ready(function(){
      $("#choose-time div").on('click', function(event){
        $(this).toggleClass("selectedBox");
          var hash = $(this).offset().top - 220;
          if(hash !== ''){
            event.preventDefault();

            $("html, body").animate({
              scrollTop: hash
            }, 900);
          }
      });
    });
Nick
  • 565
  • 4
  • 19