Skip to content

Instantly share code, notes, and snippets.

@aaronfischer
Last active August 23, 2018 19:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronfischer/7eb91217f4e96c23c25a to your computer and use it in GitHub Desktop.
Save aaronfischer/7eb91217f4e96c23c25a to your computer and use it in GitHub Desktop.
Smooth Scroll / Scroll to Section on Load
/* ----------------------------------------------------------------------------------------------------------
03 scroll to #section-id-of-div
---------------------------------------------------------------------------------------------------------- */
function smoothScroll(el, target){
// if the hash is in the URL but not on the page... ex #cosmetic-surgery but not #section-this-div
if(el !== null){
var $this = $(el),
target = el.hash,
$target = $(target);
// check if the target has an offset, if its NOT undefined then run the code to allow things to scroll
if(typeof $target.offset() != 'undefined'){
$("html, body").stop().animate({
'scrollTop': $target.offset().top
}, 500, 'swing', function () {
// add section so that it removes conflict in some browsers
window.location.hash = 'section-' + target.replace('#', '');
});
}
}
}
function scrollToSectionOnLoad(el){
var hashname = window.location.hash,
hashname = hashname.replace("section-", ""),
$this = document.querySelector('a[href="' + hashname + '"]');
smoothScroll($this);
}
/*********************************************************
/
/ Smooth Scrolling for Internal Links
/
*********************************************************/
$("body a[href^='#']").on("click", function(e, el) {
e.preventDefault();
smoothScroll(this);
});
$(window).load(function() {
//scroll to #section-ID-of-div on window load
setTimeout(function(){
scrollToSectionOnLoad();
},200);
});
@julian-kuroiwa
Copy link

Hey Aaron,

how can i make this work together (mobile and desktop)???

thankss,

Julian

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment