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;ivar 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;ivar 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
