Skip to content

Instantly share code, notes, and snippets.

@aggiedinger
Last active July 6, 2022 08:26
Show Gist options
  • Save aggiedinger/0179406445a032d56b7c674d893fdd8e to your computer and use it in GitHub Desktop.
Save aggiedinger/0179406445a032d56b7c674d893fdd8e to your computer and use it in GitHub Desktop.
To add a smooth scroll for anchor links
<!-- 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">
@goldingdamien
Copy link

Simple concept for reference:

$("a").on('click', function(event) {
  const a = this;
  const { hash } = a;
  
  event.preventDefault();

  // ... Animation and other handling.

  window.location.hash = hash;
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment