简体   繁体   中英

Applying smooth scroll when clicking an anchor link (Pure Javascript)

i'm writing the code, when the anchor link is clicked jump directcly to the specific section within the page.

here i want to make sure that the page is smoothly scrolled either up or down according to the specific section clicked through the anchor link.

although there is so many answers on stack overflow discussed the same issue but i just want to test my skills by writing my own code.

i finally notice that my code is not working and it throw many errors

i hope there is a good and better solution to improve my code

Any help will be appreciated

 function smoothScroll(){ let x = document.querySelectorAll('a[href*="#"]'); for(let i = 0; i < x.length; i++){ x[i].onclick=function(){ let target = this.hash; target.scrollIntoView({ behavior:'smooth', alignToTop:true, block:'start' }); } } } smoothScroll();
 .nav { position: relative; width: 100%; height: 60px; background-color: #111; }
 <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no"> <link type="text/css" href="/css" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <title>smoothScroll</title> </head> <body> <div class="nav"> <a href="#section1" style="color:#fff;">Link1</a> <a href="#section2" style="color:#fff;padding-left:3rem;">Link2</a> <a href="#section3" style="color:#fff;padding-left:3rem;">Link3</a> </div> <div id="section1"onclick="myFunction();" style="margin:10px auto; width:400px;"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </div> <div id="section2" style="margin:100px auto; width:400px;"> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> <div id="section3" style="margin:100px auto; width:400px;"> Where does it come from? Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. </div> </body> </html>

To fix the error, the issue is with the element reference for the scrollIntoView .

You are providing the hash value as element reference which is incorrect. You need to pass the element after selecting it with the hash value.

let target = document.querySelector(this.hash); target.scrollIntoView()

function smoothScroll(){
    let x = document.querySelectorAll('a[href*="#"]');
    for(let i = 0; i < x.length ; i++){
      x[i].onclick=function(){
      let target = document.querySelector(this.hash);
      target.scrollIntoView({
      behavior:'smooth',
      alignToTop:true,
      block:'start'
          });
         }
       }
    }
    smoothScroll();

scrollIntoView() is cross-browser compatible.

Reference: https://www.quirksmode.org/dom/w3c_cssom.html#t23

DEMO:

 function smoothScroll(){ let x = document.querySelectorAll('a[href*="#"]'); for(let i = 0; i < x.length; i++){ x[i].addEventListener('click', function(e){ e.preventDefault(); let target = document.querySelector(this.hash); target.scrollIntoView({ behavior:'smooth', alignToTop:true, block:'start' }); }); }; } smoothScroll();
 .nav { position: relative; width: 100%; height: 60px; background-color: #111; }
 <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no"> <link type="text/css" href="/css" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <title>smoothScroll</title> </head> <body> <div class="nav"> <a href="#section1" style="color:#fff;">Link1</a> <a href="#section2" style="color:#fff;padding-left:3rem;">Link2</a> <a href="#section3" style="color:#fff;padding-left:3rem;">Link3</a> </div> <div id="section1"onclick="myFunction();" style="margin:10px auto; width:400px;"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </div> <div id="section2" style="margin:100px auto; width:400px;"> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> <div id="section3" style="margin:100px auto; width:400px;"> Where does it come from? Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. </div> </body> </html>

 function smoothScroll(){ let x = document.querySelectorAll('a[href*="#"]'); for(let i = 0; i < x.length; i++){ x[i].addEventListener("click",function(){ this.scrollIntoView({ behavior:'smooth', alignToTop:true, block:'start' }); } ) } } smoothScroll();
 .nav { position: relative; width: 100%; height: 60px; background-color: #111; }
 <html lang="en-US"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=0.1,shrink-to-fit=no"> <link type="text/css" href="/css" rel="stylesheet"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <title>smoothScroll</title> </head> <body> <div class="nav"> <a href="#section1" style="color:#fff;">Link1</a> <a href="#section2" style="color:#fff;padding-left:3rem;">Link2</a> <a href="#section3" style="color:#fff;padding-left:3rem;">Link3</a> </div> <div id="section1"onclick="myFunction();" style="margin:10px auto; width:400px;"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </div> <div id="section2" style="margin:100px auto; width:400px;"> It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> <div id="section3" style="margin:100px auto; width:400px;"> Where does it come from? Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. </div> </body> </html>

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