Let's see how to jump to a marked section of the page by using the <a> tag. It's quite simple! Add an id attribute to the anchor element to give a name to the section of the page. The value of the attribute may be a word or a phrase (when using phrases remember not to have spaces, use dashes or underscores instead).
You can use anchor ( <a> ) links in HTML to link to a different page or a different website. But how can you link to a specific part of a web page? The answer is jump links. Jump links are links that won't just load the page, but they will “jump” down to a specific part of a web page.
All you need to do is set up a named link that is attached to a specific spot and a clickable link that will get you there. After that, if you want to make the transition more gradual, use jQuery and LocalScroll together. Be sure to specify both the parent container for your links and the duration of the animation.
function scrollTo(hash) {
location.hash = "#" + hash;
}
No jQuery required at all!
Way simpler:
var element_to_scroll_to = document.getElementById('anchorName2');
// Or:
var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0];
// Or:
var element_to_scroll_to = $('.my-element-class')[0];
// Basically `element_to_scroll_to` just have to be a reference
// to any DOM element present on the page
// Then:
element_to_scroll_to.scrollIntoView();
You can use jQuery's .animate(), .offset() and scrollTop
. Like
$(document.body).animate({
'scrollTop': $('#anchorName2').offset().top
}, 2000);
Example link: http://jsbin.com/unasi3/edit
If you don't want to animate, use .scrollTop() like:
$(document.body).scrollTop($('#anchorName2').offset().top);
Or JavaScript's native location.hash
like:
location.hash = '#' + anchorid;
el.scrollIntoView({
behavior: 'smooth', // smooth scroll
block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})
But as far as I understand, it does not have such good support as the options below.
Learn more about the method.
const element = document.querySelector('#element')
const topPos = element.getBoundingClientRect().top + window.pageYOffset
window.scrollTo({
top: topPos, // scroll so that the element is at the top of the view
behavior: 'smooth' // smooth scroll
})
Demonstration example on CodePen
const element = document.querySelector('#element')
const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
window.scroll({
top: rect.top + rect.height / 2 - viewHeight / 2,
behavior: 'smooth' // smooth scroll
});
Demonstration example on CodePen
Support:
They write that scroll
is the same method as scrollTo
, but support shows better in scrollTo
.
More about the method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With