-
-
Save mightyhorst/d3a105b5d5af53301514935626edd0a2 to your computer and use it in GitHub Desktop.
scroll to element vanilla 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
//from https://css-tricks.com/snippets/jquery/smooth-scrolling/ | |
// Scroll to specific values | |
// scrollTo is the same | |
window.scroll({ | |
top: 2500, | |
left: 0, | |
behavior: 'smooth' | |
}); | |
// Scroll certain amounts from current position | |
window.scrollBy({ | |
top: 100, // could be negative value | |
left: 0, | |
behavior: 'smooth' | |
}); | |
// Scroll to a certain element | |
document.querySelector('.hello').scrollIntoView({ | |
behavior: 'smooth' | |
}); | |
//jQuery way with fast example: | |
$('a.menu_items-link').on('click', function(e) { | |
e.preventDefault(); | |
const value = this.getAttribute('href'); | |
//console.log(value); | |
$('html, body').animate({ | |
scrollTop: $('#'+value).offset().top | |
}, 800, callback); | |
}); | |
/** | |
* @see ReactJs example | |
*/ | |
import {useRef, useEffect} from 'react'; | |
function Hello(){ | |
const scrollRef = useRef(); | |
useEffect(()=>{ | |
scrollRef.scrollIntoView({ | |
behavior: 'smooth' | |
}); | |
}, []); | |
return ( | |
<div ref={scrollRef}> | |
Scroll here on mount | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment