I'm using this pure JavaScript function to scroll to but want to add spacing to top, similar to what jquery - [...].offset().top - 160; - does. Any ideas? Much appreciated:
function scrollTo(hash) {
location.hash = "#" + hash;
};
Instead of reloading the whole page (Assign to location.hash does that), you can use the built-in scrollTo function...
Ho! by the way, you were overwriting it. ;)
function scrollMeTo(hash) {
let hashEl = document.querySelector("#" + hash);
if (hashEl) {
let hashPos = parseInt(hashEl.getBoundingClientRect().top) - 160;
window.scrollTo(0, hashPos);
}
}
scrollMeTo("two");
.spacer{
height: 1000px;
}
<div class="spacer"></div>
<a id="one">ONE</a>
<div class="spacer"></div>
<a id="two">TWO</a>
<div class="spacer"></div>
<a id="three">THREE</a>
<div class="spacer"></div>