Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

smooth scrolling on anchors

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);
    }
}
like image 652
msoboc4 Avatar asked Jan 23 '26 10:01

msoboc4


2 Answers

$(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.

like image 155
slevy1 Avatar answered Jan 25 '26 23:01

slevy1


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

like image 40
isp-zax Avatar answered Jan 25 '26 22:01

isp-zax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!