Skip to content

Instantly share code, notes, and snippets.

@softiconic
Last active October 29, 2024 04:31
Show Gist options
  • Save softiconic/ffc78d09ba2caecf292f450673544dcf to your computer and use it in GitHub Desktop.
Save softiconic/ffc78d09ba2caecf292f450673544dcf to your computer and use it in GitHub Desktop.
JavaScript for scrolling through pages or sections.
$(document).ready(function() {
// Define the offset
var offset = -200; // Adjust this value as needed
// Function to scroll to the target with offset
function scrollToTarget(target) {
$('html, body').animate({
scrollTop: target.offset().top + offset
}, 1000);
}
// Scroll on click
$('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
scrollToTarget(target);
return false;
}
}
});
// Scroll on page load if there's a hash in the URL
if (window.location.hash) {
var target = $(window.location.hash);
if (target.length) {
scrollToTarget(target);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment