Created
June 30, 2021 08:50
-
-
Save syofyanzuhad/8a27f776797627f44565641c102cccb0 to your computer and use it in GitHub Desktop.
smoothScrolling jquery for bootstrap
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
<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.nav-link").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(); | |
$(".nav").find(".active").removeClass("active"); | |
$(this).addClass("active"); | |
// 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 - 80 | |
}, 100, function(){ | |
// Add hash (#) to URL when done scrolling (default click behavior) | |
window.location.hash = hash; | |
}); | |
} // End if | |
}); | |
// Detect id in url and scrolling | |
if (location.hash) { | |
$('nav li a[href^="' + location.hash + '"]').trigger('click'); | |
} else { | |
$('nav li a[href^="#beranda"]').addClass('active'); | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment