I'm using Bootstrap 4, and am using the following jQuery to allow smooth scrolling from the .nav-links to section id's (within the same page):
$('.nav-link').click(function() {
var sectionTo = $(this).attr('href');
$('html, body').animate({
scrollTop: $(sectionTo).offset().top
}, 1500);
});
This works great for .nav-link items, but if I try to add other classes, the code does not work on them. eg, I add .navbar-brand and .new-button:
$('.nav-link, .navbar-brand, .new-button').click(function() {
var sectionTo = $(this).attr('href');
$('html, body').animate({
scrollTop: $(sectionTo).offset().top
}, 1500);
});
Any help greatly appreciated.
Set scroll-behavior in css and it will do the effect.
html {
scroll-behavior: smooth;
}
Here's a link to the example: https://jsfiddle.net/mzjan/set7aLnp/
Its working fine with bootstrap 4 and this code also working fine may be something wrong in your other code.
$('.test, .nav-link, .navbar-brand, .new-button').click(function() { var sectionTo = $(this).attr('href'); $('html, body').animate({ scrollTop: $(sectionTo).offset().top }, 1500); });
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <a href="#one" class="test">test class</a><br> <a href="#two" class="navbar-brand">navbar-brand class</a> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <div id="one">test class</div> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <div id="two">navbar-brand class</div> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.