Last active
August 23, 2018 19:19
-
-
Save aaronfischer/7eb91217f4e96c23c25a to your computer and use it in GitHub Desktop.
Smooth Scroll / Scroll to Section on Load
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
/* ---------------------------------------------------------------------------------------------------------- | |
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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey Aaron,
how can i make this work together (mobile and desktop)???
thankss,
Julian