Skip to content

Instantly share code, notes, and snippets.

@sohelaman
Last active April 22, 2021 13:34
Show Gist options
  • Save sohelaman/c100a80a069667c00e2ba7e1f0c2da5b to your computer and use it in GitHub Desktop.
Save sohelaman/c100a80a069667c00e2ba7e1f0c2da5b to your computer and use it in GitHub Desktop.
[JavaScript] JavaScript misc snippets #js
/**
* Scroll to an element
*/
(function() {
var element = document.getElementById("myAwesomeDiv");
var elementTop = element.getBoundingClientRect().top;
if (elementTop < 0) {
// check if the top of the element is outside the top of the viewport.
var y = elementTop + window.scrollY - 5;
window.scroll({
top: y,
behavior: 'smooth'
});
}
// same thing without much complexity
element.scrollIntoView({behavior: 'smooth'});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment