0

I'm trying to scroll to a certain section on on my website this section is marked with an ID and I want to do so using an animated jquery scroll on a click event. This is my current code:

js header section

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script src="index.js"></script>

Menu area

<li><a onclick="scrollTo()" href="#testimonials">Testimonials</a></li>
<li><a onclick="scrollTo()" href="#portfolio">Portfolio</a></li>
<li><a onclick="scrollTo()" href="#contact">Contact</a></li>
<li><a onclick="scrollTo()" href="#faq">FAQ</a></li>

Javascript file

$(document).ready(function() {
    console.log("Test")
    function scrollTo() {
        console.log("Clicked!")
        var elem = document.getElementById('testimonials');
        console.log(elem)
        elem.scrollTop = elem.scrollHeight;
        window.scrollTo
    }
})
K A
  • 115
  • 1
  • 10

1 Answers1

0

See it here: codepen

Firstly : Don't use scrollTo for your handler name. because scrollTo is a function in js.


Additional Steps:

  1. Add inline events to your navigation elements like this:
<a onclick="scrollTo_(event,'testimonials')" href="#testimonials">Testimonials</a>

It will pass click event and also an id to let the handler know what's the target element's id.

  1. Handler function should be like this:
function scrollTo_(ev,id) {
  ev.preventDefault();
  $([document.documentElement, document.body]).animate({
    scrollTop: $("#"+id).offset().top
  }, 2000);
}

It's using preventDefault to prevent normal <a> click behavior. and it use this answer (how to animate scroll with jquery) for animate scroll to element with jquery.


Additional notes:

  • Don't put your function declarations inside $(document).ready.
yaya
  • 4,522
  • 1
  • 19
  • 24