// What this module does:
//
// If you click on an anchor link, this will extract the id from the href, find an element in the DOM with that id (target) and smoothscroll to that position. getOffset adds an Offset of your choice to the targetPosition.
//
// Install smoothscroll-polyfill:
// `npm i smoothscroll-polyfill` or `yarn add smoothscroll-polyfill`
//
// Import and call this module ('DOMContentLoaded' is optional):
// import smoothAnchorScroll from './path-to/smooth-anchor-scroll';
//
// document.addEventListener('DOMContentLoaded', () => {
// smoothAnchorScroll();
// });
//
import smoothscroll from 'smoothscroll-polyfill';
export default function() {
const anchors = document.querySelectorAll('a[href*="#"]:not([href="#"])');
/**
* Get Offset for anchor link smooth scroll. This will be substracted from the targetPosition.
* @returns {Number} Offset in px
*/
const getOffset = () => {
let offset = 0;
const designRelatedOffset = 30;
offset += designRelatedOffset;
const header = document.querySelector('.my-fixed-element');
if (header) {
offset += header.clientHeight;
}
return offset;
};
if (anchors) {
// kick off the smoothscroll polyfill!
smoothscroll.polyfill();
// Loop over anchors
anchors.forEach(element => {
element.addEventListener('click', event => {
// Prevent default behaviour of anchor link
event.preventDefault();
/** @type {String} */
let targetId;
/** @type {HTMLElement} */
let target;
/** @type {Number} */
let targetPosition;
// We expect element.getAttribute('href') to be something like #foo or #bar so we cut away the '#' to receive the id
targetId = element.getAttribute('href').substring(1);
if (targetId) {
target = document.getElementById(targetId);
if (target) {
targetPosition = target.offsetTop - getOffset();
// Scroll to targetPosition
window.scrollTo({
top: targetPosition,
left: 0,
behavior: 'smooth'
});
}
}
});
});
}
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.