简体   繁体   中英

Smooth Scroll Won't Work on Bootstrap 4 Website

I added IDs and the smooth scroll effect won't work. It doesn't even scroll up to the ID that I assign it. I tested it in a test HTML file and it worked. I thought it was because some of my responsive elements didn't have fixed heights, but when I gave them fixed heights, it still did not work.

I tried to copy and paste my code. However, it said I have formatting problems no matter what I did. So I created a pastebin link: https://pastebin.com/raw/dfQS9RUA

        <script>
      $(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(){

              alert("SCROLL CODE RUNNING");

              // Add hash (#) to URL when done scrolling (default click behavior)
              window.location.hash = hash;
            });
          } // End if
        });
      });
      </script>

      <a href="#homepage">Click Me to Smooth Scroll to Section 1 Above</a>

I found that I get this error in the console:

index.html:30 Uncaught TypeError: $(...).animate is not a function
at HTMLAnchorElement.<anonymous> (index.html:30)
at HTMLAnchorElement.dispatch (jquery-3.4.1.slim.min.js:2)
at HTMLAnchorElement.v.handle (jquery-3.4.1.slim.min.js:2)

This implies that I do not have the right version of JQuery installed, but when I make the CDN the uncompressed version or the slim version, it still does not work.

This is the CDN of JQuery I am using:

        <script
    src="https://code.jquery.com/jquery-3.5.0.min.js"
    integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ="
    crossorigin="anonymous"></script>

https://codepen.io/tmoses/pen/zYvzZmo

https://code.jquery.com/jquery-3.4.1.min.js

Change the above in your bootstrap scripts, and remove the other. For some reason the slim version didn't load the animate function, but it works with just the minified version. It also appears the "integrity" attribute was causing it not to load properly. Try not to combine several versions of jQuery in one document.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM