Skip to content

Instantly share code, notes, and snippets.

@miladd3
Last active January 6, 2020 12:32
Show Gist options
  • Save miladd3/92ee2d6e400fc228e36b4e8e8a2f0d6f to your computer and use it in GitHub Desktop.
Save miladd3/92ee2d6e400fc228e36b4e8e8a2f0d6f to your computer and use it in GitHub Desktop.
Vanilla Javascript smooth scrolling with some options (uses Es6 and behavior)
/**
* Smooth scroll to element (just modern browsers)
* @param {HTMLElement|String} elm
* @param options
*
* @example scrollTo('.element img');
* @example scrollTo(document.getElementById('element'))
*/
const scrollTo = (elm, options = {
offset: 0,
delay: 0
}) => {
if (!elm) {
return;
}
let element = elm;
const doScroll = () => {
if (typeof elm === 'string') {
element = document.querySelector(elm);
}
let offset = options.offset ? element.offsetTop - options.offset : element.offsetTop;
try {
if (element.offsetTop) {
window.scroll({
behavior: 'smooth',
left: 0,
top: offset
});
} else {
console.error('element has no offsetTop !')
}
} catch (e) {
console.error(e);
}
};
if (options.delay && options.delay > 0) {
setTimeout(doScroll, options.delay)
} else {
doScroll();
}
};
export default scrollTo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment