-3

Hi I'm developing a site and I'd like to make people scroll to an href id without showing it in the navigation bar of their browsers. If is it possible I'd like to do it with

Am I able to do it? Thanks

Example: index.html#id

How I want it: index.html

Burgo
  • 31
  • 1
  • 1
  • 3

2 Answers2

2

You can use Element.scrollIntoView to achieve this. The javascript needed is

var scrollToElement = function(id){
    document.getElementById(id).scrollIntoView();
}

If you pass in {behaviour: 'smooth'} to the function you get smooth scrolling which is really slick.

Check https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView for further documentation on this function

FSeidl
  • 317
  • 1
  • 4
-1

pure JS version

Using window.scrollTo(x,y) you can move the viewport:

var elem = document.getElementById("your element id");
window.scrollTo(0, elem.offsetTop);

jQuery Version

If you are already using jQuery, you can use .animate() for a smooth scroll transition to the element.

Here is an example:

$("#button").click(function() {
    $('html, body').animate({
        scrollTop: $("#elementtoScrollToID").offset().top
    }, 2000);
});

See also here

rollstuhlfahrer
  • 3,762
  • 9
  • 21
  • 37