I’d like to make the browser to scroll the page to a given anchor, just by using JavaScript.
I have specified a name
or id
attribute in my
In 2018, you don't need jQuery for something simple like this. The built in scrollIntoView() method supports a "behavior
" property to smoothly scroll to any element on the page. You can even update the browser URL with a hash to make it bookmarkable.
From this tutorial on scrolling HTML Bookmarks, here is a native way to add smooth scrolling to all anchor links on your page automatically:
let anchorlinks = document.querySelectorAll('a[href^="#"]')
for (let item of anchorlinks) { // relitere
item.addEventListener('click', (e)=> {
let hashval = item.getAttribute('href')
let target = document.querySelector(hashval)
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
})
history.pushState(null, null, hashval)
e.preventDefault()
})
}