What is the best way to achieve smooth scrolling on a webpage?

I am looking to create a smooth animated scroll effect on page load to a specific position using jQuery's animate function:

$(document).ready(function () {
    $('html, body').animate({
        scrollTop: $('#today').offset().top - 50
    }, 800, "linear");
});

While the current implementation works, it is not as fluid, especially on mobile devices where it feels jerky.

I have come across CSS animations that are very smooth utilizing transitions and transforms. I am wondering if it is possible to achieve the same smooth scrolling effect using CSS instead of jQuery?

Answer №1

Make your scrolling smoother with this CSS:

<style type="text/css">
    html {
      scroll-behavior: smooth !important;
    }
</style>

Enhance the scroll behavior using vanilla JavaScript rather than jQuery:

function scrollToElement(elementId) {
    var element = document.getElementById(elementId);
    element.scrollIntoView({behavior: "smooth"});
}
scrollToElement('today')

Add an intermediary element in between sections for improved scrolling:

<div id="middle" style="display: none;"></div>

function scrollToElement(elementId) {
    var middleElement = document.getElementById('middle');
    var element = document.getElementById(elementId);
    middleElement.scrollIntoView({behavior: "instant"});  
    element.scrollIntoView({behavior: "smooth"});
}
scrollToElement('today')

Learn more about scrollIntoView here: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

If you're experiencing slow scrolling on iOS, check out this resource: Scrolling slow on mobile/ios when using overflow:Scroll

Answer №2

Consider trying the easing function called easeOutCubic for a smoother animation effect (you can find other options here):

$(document).ready(function () {
    $('html, body').animate({
        scrollTop: $('#today').offset().top - 50
    }, 800, "easeOutCubic");
});

Answer №3

After much research, I have discovered that the most effective solution for achieving a smooth scrollTop experience across different browsers and devices is through the use of velocity.js. This library surpasses jQuery's animate in terms of speed, efficiency, and flexibility, making it a valuable asset for frontend web developers. By simply replacing .animate() with .velocity() (and ensuring proper loading), users can seamlessly enhance their scrolling animations.

While there may be other options available, I have found velocity.js to be reliable and continually updated, making it a must-have tool for any serious developer. Check out the impressive list of websites utilizing velocity on their libscore page - you'll see why this resource is highly regarded by many. And just to clarify, I am not associated with velocity.js; I am simply grateful for the opportunity to utilize such a powerful tool at no cost.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I achieve a pixelated texture effect using three.js?

I revamped a demo similar to Minecraft where you can jump and build blocks. However, the texture of the blocks I create appears smooth instead of pixelated, and I'm not sure why. Here is the relevant source code snippet: var textureDirt = THREE.Imag ...

Is it necessary to always pause before I click?

Currently, I am in the process of writing tests for my website using WebdriverIO with Mocha and Chai. However, I encountered an issue where my element is not rendered before attempting to interact with it. it('select application', function(done) ...

Execute HTML code within a text field

Is it possible to run html code with javascript inside a text box, similar to w3schools.com? I am working solely with html and javascript. Thank you. For example, I have two text areas - one for inserting html, clicking a button to run the code, and displ ...

How to Position Input Fields over an Image Using CSS

I am working on positioning input fields over an image to allow data entry directly onto the image itself. https://i.sstatic.net/jW4iM.png Currently, I have a series of input fields (shown above) and three images with different squares on them. My goal is ...

Node/Express API returning empty body when being accessed through fetch or axios requests

Currently working on integrating an API call in a React app using Node/Express. No matter where I place the fetch/axios call, the parsed body always shows up as undefined in my controller. Yesterday, I was experimenting with fetch but decided to switch to ...

Converting an Ajax request from JavaScript to jQuery

I am new to Ajax and trying to convert an ajax request from javascript to jquery without success. Here is the javascript code snippet I am working with: function aaa(track_id) { var req = new XMLHttpRequest(); req.open("get", "list.php?tr=" + track_id, ...

What are the methods for accessing data from a local Json file on an html page without using a server?

Looking to access a local Json file from an HTML page, but encountering challenges in reading the file on Chrome and IE. Is there a method to achieve this without relying on a web server? ...

Struggling to get PHP json_encode to work with jQuery?

While developing a website on my computer, I had no trouble getting AJAX requests with jQuery to work smoothly. However, when moving the site to the production server, I encountered some issues. This is how the CodeIgniter controller I have handles return ...

Error encountered while deploying React app on Netlify due to absence of build scripts

I recently deployed a React app on Netlify from GitHub. Unfortunately, the deployment status showed as failed with the following error: Mar 27: Failed during the stage of 'building site': Build script returned a non-zero exit code: 1 I als ...

Using file types in Vue 3: a beginner's guide

In order to use file-type to determine not only the extension but also ensure the headers are correct I would need to use one of the methods listed on their GitHub page. In version 19.0.0 it says fileFromFileType doesn't have such an export and in 16. ...

Having trouble getting user input?

I'm facing a dilemma because I am unsure of how to capture the user's input. Currently, my objective is simply to display what the user types into an input box without performing any calculations. var x = document.getElementById('textboxone ...

Mastering form submission with Node.js and enhancing it with JQueryMobile

I'm currently working on a project that involves using node.js and jQuery Mobile, but I've encountered some issues with managing the form submission. Can anyone provide guidance on how to navigate to the next page? What parameters should be passe ...

Once you utilize the register function with react-hook-form, the input text becomes uneditable

Struggling to configure react-fook-form for form validation, I encountered an issue where the text input (specifically the username field) becomes uneditable after using the register function. Despite my efforts, I can't type anything into it. const { ...

Is it possible to maintain the maximum height and width of a div across all levels of zoom?

In the process of developing a web application, I encountered an issue regarding setting the width and height of a div to a fixed number, regardless of the zoom level. While I was successful in changing the background color of the div across all zoom level ...

Is there an advantage to pre-rendering a circle on an HTML5 canvas for improved performance?

Is it more efficient to pre-render graphics for a basic shape like a circle on an off-screen canvas? Would there be noticeable improvements in rendering performance when dealing with 100 circles at game-like framerates? What about 50 circles or just 25? ...

Tips on achieving vertical movement within a div element from the bottom of the wrapper to the

I am struggling to animate a .alert div within its wrapper to fly up from the bottom of the wrapper by 40px. However, I am encountering difficulty as the alert div does not start at the bottom of the wrapper as intended. The desired behavior is for it to s ...

Expanding Overlay Width in Vuejs and CSS for Small Devices under 500px

How can I adjust the width of the overlay nav specifically for small devices in Vue or CSS? My current width is set to 25% for devices with a width of 1000px or more, but I need a different width of 35% or more for smaller devices to improve text visibilit ...

Framework designed to be compatible with Internet Explorer 7 for seamless

Is there a CSS framework that provides full support for IE7 without any issues? Specifically, something similar to Twitter Bootstrap but with guaranteed rounded corners and properly functioning tabs. I have experienced problems with the Popover plugin sp ...

Looking for assistance in designing a responsive web page with CSS, specifically in determining the optimal page width

Currently, I am working on making my web page responsive for four different screen sizes (320px, 640px, 980px, and 1024px). Everything looks great and adapts well when I resize the site up to 1024px. However, once the size goes beyond that, I want to preve ...

Babeljs encountered an error: TypeError - The super expression should be a function or null, not undefined

Currently, my project involves implementing multiple-files inheritance in ES6 using Node.js and Babel. Babel is used to convert the ES6 code to ES5 since Node does not fully support ES6 yet. Import/export statements are used to connect the different files ...