Last active
October 29, 2024 04:31
-
-
Save softiconic/ffc78d09ba2caecf292f450673544dcf to your computer and use it in GitHub Desktop.
JavaScript for scrolling through pages or sections.
This file contains hidden or 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
$(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