Last active
July 6, 2022 08:26
-
-
Save aggiedinger/0179406445a032d56b7c674d893fdd8e to your computer and use it in GitHub Desktop.
To add a smooth scroll for anchor links
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
<!-- Smooth Scroll --> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/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 !== "learn") { | |
// 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> | |
<!-- This is the code for your anchor where you want people to land. Quick and easy. Do not paste with code above --> | |
<a name="learn"></a> | |
<!-- This is the code for your anchor if you want smooth scrolling. Do not paste with code above --> | |
<div class="main" id="learn"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple concept for reference: