Reputation: 93
I want to add a smooth scroll effect when i click a button in my navbar. It jumps to the link but no smooth scroll effect
My section code:
<section id="home"></section>
And here is the button associated to it
<a class="nav-link" href="#home">home</a>
Here are some JS scripts that I tried but none of them worked
$(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
The second one
$(document).ready(function() {
// check for hash when page has loaded
if (getHash() != null) {
checkForScrolling();
}
});
// listen for hash change event here
window.onhashchange = function() {
checkForScrolling();
};
// return hash if so or null if hash is empty
function getHash() {
var hash = window.location.hash.replace('#', '');
if (hash != '') {
return hash;
} else {
return null;
}
}
// this function handles your scrolling
function checkForScrolling() {
// first get your element by attribute selector
var elem = $('[data-anchor="' + getHash() + '"]');
// cheeck if element exists
if (elem.length > 0) {
$('html, body').stop().animate({
scrollTop: elem.offset().top
}, 300);
}
}
Upvotes: 2
Views: 4296
Reputation: 3832
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('mouseover', 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
});
});
body, html, .main {
height: 100%;
}
section {
width:80%;
height:80%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<section id="home">HOME
<br><a class="nav-link" href="#myAnchor">go2end</a>
</section>
<div class="main">
<section style="background-color:blue"></secion>
</div>
<a id="myAnchor" class="nav-link" href="#home">home</a>
What is being scrolled is the page, so to best reference it you need this code when using jQuery:
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
The correction by @bru02 is astute and so I use that code to demonstrate the smooth scrolling effect. However, I change the code so that a user need only mouseover the link instead of clicking it -- more comfortable for saving one's wrist. And, provide HTML so that one may scroll up or down the page, too.
The script itself apparently originates from here and works there, too. The script as cited by the OP only failed because of an incomplete copy/paste.
Upvotes: 3
Reputation: 16855
Try to use attr()
to get the id
value then set scrollTop
value to the particular id offset().top
and use animate()
for smooth scroll on click
Stack Snippet
$(document).on("click", ".nav-link", function(e) {
e.preventDefault();
var hash = $(this).attr("href");
if ($(hash).length === 0) {
return;
}
//console.log($(hash).offset().top)
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="nav-link" href="#home">home</a>
<a class="nav-link" href="#about">about</a>
<div class="other-section">
other-section<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
</div>
<section id="home">
<h1>Home</h1>
</section>
<div class="other-section">
other-section<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
<br> other-section
</div>
Upvotes: 2
Reputation: 360
You forgott the closing brackets after the }); } // End if
part.
So if you paste this }); });
to the first one's bottom it will work fine.
The finished code looks like this:
$(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
});
});
Upvotes: 2
Reputation: 3873
Amusing this is not a request to debug your code, here is a working example
// Select all links with hashes
$('a[href*="#"]')
// Remove links that don't actually link to anything
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
// On-page links
if (
location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
&&
location.hostname == this.hostname
) {
// Figure out element to scroll to
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top
}, 1000, function() {
// Callback after animation
// Must change focus!
var $target = $(target);
$target.focus();
if ($target.is(":focus")) { // Checking if the target was focused
return false;
} else {
$target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
$target.focus(); // Set focus again
};
});
}
}
});
and description is here
Upvotes: 2