0

I've found a few posts on here similar to what I'm asking, but they all involve jQuery (I'm looking for a solution that's purely javascript, as simple as possible).

I have a page with a fixed nav on the left, where the different links bring you up or down to different sections on the page. It works fine, but I was trying to find a way to animate the scroll. I managed to come up with some javascript that tells me the offset between the sections:

function scroll(e) {
   dest = e.target.getAttribute('href'); 

(for example, this would give me the result of #aboutCon)

   destination = dest.replace("#", "");

(this changed it to aboutCon which is already defined as a variable containing the "About" section)

   var destOffset = window[destination].offsetTop;
   window.scrollTo(0, destOffset); 
}

but I have no idea how to take that information and animate it. I've found a few javascript solutions but they're so complicated, whenever I try applying them to my own code, they don't work. I'm hoping there's a simple way to achieve this?

I'm a student and still learning so if you have an answer, an accompanying explanation would be greatly appreciated! Thank you!

aramjam
  • 21
  • 2
  • Possible duplicate of [Scroll smoothly to specific element on page](http://stackoverflow.com/questions/17722497/scroll-smoothly-to-specific-element-on-page) – Nick Zuber Dec 02 '15 at 00:53
  • 1
    That was actually incredibly helpful, thank you! – aramjam Dec 02 '15 at 16:26

1 Answers1

0
document.getElementById("elementID").scrollIntoView();

Or cleaning it up a bit...

function scrollIntoView(eleID) { 
   var e = document.getElementById(eleID); 
   if (!!e && e.scrollIntoView) {
       e.scrollIntoView();
   }
}

Of course replace "elementID" with the ID of the div or element you want to scroll to.

This one is the simplest solution I've found with pure JS.

  • This is why we have JQuery. It fixes a lot of the cross browser compatibility. Just use this JQuery CDN and script and it should do what you need plus animate it nicely. $('html, body').animate({ scrollTop: $("#elementtoScrollToID").offset().top }, 2000); – Robert Hosking Dec 03 '15 at 23:45