Home >Web Front-end >JS Tutorial >Make Internal Links Scroll Smoothly with JavaScript

Make Internal Links Scroll Smoothly with JavaScript

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2025-03-08 00:43:10733browse

Make Internal Links Scroll Smoothly with JavaScript

This approach follows the principles of unobtrusive DHTML, making it easy for everyone to use. For the solution to work, the script needs to be run by something; we put the code from our first step (looping over the links to find those that are internal) into a function ss_fixAllLinks(), and bind that to the window’s onload event using Scott Andrew’s function:

ss_addEvent(window,"load",ss_fixAllLinks);

The whole code looks like this:

function ss_fixAllLinks() {   
 // Get a list of all links in the page  
 var allLinks = document.getElementsByTagName('a');  
 // Walk through the list  
 for (var i=0;i    var lnk = allLinks[i];  
   if ((lnk.href && lnk.href.indexOf('#') != -1) &&    
       ( (lnk.pathname == location.pathname) ||  
   ('/'+lnk.pathname == location.pathname) ) &&    
       (lnk.search == location.search)) {  
     // If the link is internal to the page (begins in #)  
     // then attach the smoothScroll function as an onclick  
     // event handler  
     ss_addEvent(lnk,'click',smoothScroll);  
   }  
 }  
}  
 
function smoothScroll(e) {  
 // This is an event handler; get the clicked on element,  
 // in a cross-browser fashion  
 if (window.event) {  
   target = window.event.srcElement;  
 } else if (e) {  
   target = e.target;  
 } else return;  
   
 // Make sure that the target is an element, not a text node  
 // within an element  
 if (target.nodeType == 3) {  
   target = target.parentNode;  
 }  
   
 // Paranoia; check this is an A tag  
 if (target.nodeName.toLowerCase() != 'a') return;  
   
 // Find the tag corresponding to this href  
 // First strip off the hash (first character)  
 anchor = target.hash.substr(1);  
 // Now loop all A tags until we find one with that name  
 var allLinks = document.getElementsByTagName('a');  
 var destinationLink = null;  
 for (var i=0;i    var lnk = allLinks[i];  
   if (lnk.name && (lnk.name == anchor)) {  
     destinationLink = lnk;  
     break;  
   }  
 }  
   
 // If we didn't find a destination, give up and let the browser do  
 // its thing  
 if (!destinationLink) return true;  
   
 // Find the destination's position  
 var destx = destinationLink.offsetLeft;    
 var desty = destinationLink.offsetTop;  
 var thisNode = destinationLink;  
 while (thisNode.offsetParent &&    
       (thisNode.offsetParent != document.body)) {  
   thisNode = thisNode.offsetParent;  
   destx += thisNode.offsetLeft;  
   desty += thisNode.offsetTop;  
 }  
   
 // Stop any current scrolling  
 clearInterval(ss_INTERVAL);  
   
 cypos = ss_getCurrentYPos();  
   
 ss_stepsize = parseInt((desty-cypos)/ss_STEPS);  
 ss_INTERVAL = setInterval('ss_scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);  
   
 // And stop the actual click happening  
 if (window.event) {  
   window.event.cancelBubble = true;  
   window.event.returnValue = false;  
 }  
 if (e && e.preventDefault && e.stopPropagation) {  
   e.preventDefault();  
   e.stopPropagation();  
 }  
}  
 
function ss_scrollWindow(scramount,dest,anchor) {  
 wascypos = ss_getCurrentYPos();  
 isAbove = (wascypos < dest);  
 window.scrollTo(0,wascypos + scramount);  
 iscypos = ss_getCurrentYPos();  
 isAboveNow = (iscypos < dest);  
 if ((isAbove != isAboveNow) || (wascypos == iscypos)) {  
   // if we've just scrolled past the destination, or  
   // we haven't moved from the last scroll (i.e., we're at the  
   // bottom of the page) then scroll exactly to the link  
   window.scrollTo(0,dest);  
   // cancel the repeating timer  
   clearInterval(ss_INTERVAL);  
   // and jump to the link directly so the URL's right  
   location.hash = anchor;  
 }  
}  
 
function ss_getCurrentYPos() {  
 if (document.body && document.body.scrollTop)  
   return document.body.scrollTop;  
 if (document.documentElement && document.documentElement.scrollTop)  
   return document.documentElement.scrollTop;  
 if (window.pageYOffset)  
   return window.pageYOffset;  
 return 0;  
}  
 
function ss_addEvent(elm, evType, fn, useCapture)  
// addEvent and removeEvent  
// cross-browser event handling for IE5+,  NS6 and Mozilla  
// By Scott Andrew  
{  
 if (elm.addEventListener){  
   elm.addEventListener(evType, fn, useCapture);  
   return true;  
 } else if (elm.attachEvent){  
   var r = elm.attachEvent("on"+evType, fn);  
   return r;  
 }  
}    
 
var ss_INTERVAL;  
var ss_STEPS = 25;  
 
ss_addEvent(window,"load",ss_fixAllLinks);
Wrapping Up

Your document internal links will scroll to their destination, allowing your users to retain an awareness of where the browser is located within the document, and how far they are from their starting point. The code has been tested and works in Mozilla, IE, and Opera; it doesn’t work in Konqueror, and is assumed to not work in other browsers.

Frequently Asked Questions (FAQs) about Smooth Scrolling with JavaScript

How can I implement smooth scrolling in JavaScript?

Implementing smooth scrolling in JavaScript involves using the window.scrollTo method. This method takes two arguments: the x-coordinate and the y-coordinate to which the window should scroll. To make the scrolling smooth, you can use the behavior property and set it to ‘smooth’. Here’s a simple example:

window.scrollTo({
top: 0,
behavior: 'smooth'
});
This code will smoothly scroll the window to the top of the page.

Can I use JavaScript to scroll to a specific element on the page?

Yes, you can use JavaScript to scroll to a specific element on the page. You can do this by first selecting the element using a method like document.querySelector, and then using the scrollIntoView method on the selected element. Here’s an example:

var element = document.querySelector('#myElement');
element.scrollIntoView({behavior: 'smooth'});
This code will smoothly scroll the window to the element with the id ‘myElement’.

What browsers support smooth scrolling with JavaScript?

The smooth scrolling feature in JavaScript is supported by most modern browsers, including Chrome, Firefox, Safari, and Edge. However, it’s not supported by Internet Explorer. You can check the compatibility table on the MDN Web Docs for the most up-to-date information.

Can I control the speed of the smooth scrolling?

The speed of the smooth scrolling is determined by the browser and cannot be directly controlled with JavaScript. However, you can create a custom smooth scrolling function with a set speed by using the window.requestAnimationFrame method.

How can I implement smooth scrolling with JavaScript for anchor links?

You can implement smooth scrolling for anchor links by adding an event listener for the ‘click’ event on the links. In the event handler, you can prevent the default action of the link, which is to instantly navigate to the target element, and instead use the scrollIntoView method to smoothly scroll to the target element. Here’s an example:

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();

document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
This code will add smooth scrolling to all anchor links on the page.

Can I add a scroll offset when using smooth scrolling with JavaScript?

Yes, you can add a scroll offset when using smooth scrolling with JavaScript. You can do this by subtracting the desired offset from the y-coordinate in the scrollTo method or the top property in the scrollIntoView method.

Can I use jQuery to implement smooth scrolling?

Yes, you can use jQuery to implement smooth scrolling. jQuery provides the animate method, which you can use to animate the scrollTop property of the html and body elements. Here’s an example:

$('html, body').animate({
scrollTop: $("#myElement").offset().top
}, 2000);
This code will smoothly scroll the window to the element with the id ‘myElement’ over a period of 2 seconds.

Can I implement smooth scrolling with CSS instead of JavaScript?

Yes, you can implement smooth scrolling with CSS by using the scroll-behavior property. You can set this property to ‘smooth’ on the html or body element to enable smooth scrolling for the whole page. However, this method has less browser support than the JavaScript method.

How can I test if smooth scrolling is working correctly?

You can test if smooth scrolling is working correctly by simply trying to scroll on your page. If the scrolling is smooth and not instant, then it’s working correctly. You can also use the developer tools in your browser to inspect the scroll behavior.

Can I disable smooth scrolling with JavaScript?

Yes, you can disable smooth scrolling with JavaScript by simply not using the behavior property in the scrollTo or scrollIntoView methods, or by setting it to ‘auto’. This will make the scrolling instant instead of smooth.

The above is the detailed content of Make Internal Links Scroll Smoothly with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn