So earlier I wrote a small snippet of code to implement a smooth scroll on my webpage. Initially it was working fine, but as developing progressed it randomly stopped working and has not started working since. Now when it scrolls there is a delay from when you press the button and then eventually it snaps to the part of the page its targeting.
Here is the script tag for the library:
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/smooth-scroll@15.0.0/dist/smooth-scroll.polyfills.min.js"></script>
And here is the javascript:
const scroll = new SmoothScroll('nav a[href*="#"]',{
speed: 800
});
I do not want to use the CSS scroll-behavior: smooth because most of my sites traffic will be on Safari which doesn't support that.
For browsers that do not support the scroll-behavior property, you could use JavaScript or a JavaScript library, like jQuery, to create a solution that will work for all browsers:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>