Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap 4. Smooth scrolling working on .nav-link but not on other anchor elements

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.

like image 494
FruityPixels Avatar asked Mar 08 '18 12:03

FruityPixels


2 Answers

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/

like image 144
Janek Avatar answered Nov 16 '22 01:11

Janek


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>
like image 28
Rohit Verma Avatar answered Nov 16 '22 00:11

Rohit Verma