Last active
April 22, 2021 13:34
-
-
Save sohelaman/c100a80a069667c00e2ba7e1f0c2da5b to your computer and use it in GitHub Desktop.
[JavaScript] JavaScript misc snippets #js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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