What is the best way to smoothly scroll to another page using a specific id?

My website consists of multiple pages and I am looking for a code that will allow for smooth scrolling navigation to another page when loading on a specific id or section.

For example, in the navbar I have multiple pages with links. When clicking on a link in the navbar, I want to navigate to the corresponding page and smoothly scroll down to the section containing the information related to that link.

I have managed to achieve this using only HTML, but without the smooth scrolling effect. Currently, clicking on a navbar link navigates me to the appropriate section on the other page.

I hope my explanation is clear enough to understand.

Answer №1

Modern web browsers have the ability to detect the hash in the URL and automatically navigate to that specific section. However, if you prefer smooth scrolling instead of instant jumping, you can reset the scroll position to the top and then apply smooth scrolling.

Include the following script:

// Scroll to top immediately
if (window.location.hash)
    scroll(0,0);
// Resolve some browser issues
setTimeout(function(){scroll(0,0);},1);

Now, attempt to access the anchor from another page and observe how the browser smoothly scrolls to the top without abruptly jumping to the anchor element.

Next, implement smooth scrolling:

$(function(){
// Handle click event
$('.scroll').on('click',function(e){
    e.preventDefault();
    $('html,body').animate({
        scrollTop:$($(this).attr('href')).offset().top + 'px'
    },1000,'swing');
});

// Smooth scroll when accessed via anchor in URL
if(window.location.hash){
    // Scroll smoothly to the anchor id
    $('html,body').animate({
        scrollTop:$(window.location.hash).offset().top + 'px'
        },1000,'swing');
    }
});

Following these steps will ensure a seamless experience. You will be directed to the anchor element on another page with a smooth scrolling effect.

Complete script:

// Scroll to top immediately
if (window.location.hash)
    scroll(0,0);
// Resolve some browser issues
setTimeout(function(){scroll(0,0);},1);

$(function(){
// Handle click event
$('.scroll').on('click',function(e){
    e.preventDefault();
    $('html,body').animate({
        scrollTop:$($(this).attr('href')).offset().top + 'px'
    },1000,'swing');
});

// Smooth scroll when accessed via anchor in URL
if(window.location.hash){
    // Scroll smoothly to the anchor id
    $('html,body').animate({
        scrollTop:$(window.location.hash).offset().top + 'px'
        },1000,'swing');
    }
});

Answer №2

To achieve smooth scrolling in your CSS file, simply include the following:

html {
    scroll-behavior: smooth;
} 

Then, make sure to specify the ID in the href attribute like this:

href="file_where_the_element_is.html#ID_of_the_element

For example:

<a href="index.html#contentID>

It's as easy as that! No need for JS or JQuery, just CSS and HTML.

Answer №3

Consider implementing smooth scrolling within the $(window).load function instead of $(document).ready. Scrolling in $(document).ready may result in the page scrolling to an incorrect position if images have not finished loading.

$(document).ready(function () {
    if (window.location.hash) {
        scroll(0, 0);
    }
}

$(window).load(function() {
    if (window.location.hash) {
        const hash = window.location.hash;
        $('html, body').animate({
            scrollTop : $(hash).offset().top
        }, 500);
    }
});

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

Pass data in JSON format from Laravel controller to AngularJS

When working with Laravel, I successfully converted data in MySQL to JSON for use in AngularJS. However, I am now unsure of how to effectively utilize these values in AngularJS. Can anyone offer assistance? View output data (hide each value) Controller ...

Enhance the functionality of a directive by incorporating the ui-mask directive

Recently, I implemented a custom directive for an input field that adds a calendar icon with a datepicker to the input. I have used this directive in various sections of my application and now I am interested in incorporating ui-mask - another directive I ...

What's up with this unconventional jQuery formatting? Can someone shed some light on

I recently found a plugin that toggles checkboxes, but unfortunately it's not functioning correctly with the latest version of jQuery so I'm currently working on debugging it. Could someone please provide an explanation for the following code sn ...

What is the best way to alter the header in Django when a user is authenticated?

In my project, I have two headers: header.html and headersuccess.html. When a user is logged in, I need to change the header from header.html to headersuccess.html. How can I implement that? Here is an excerpt from my views.py file where I render loginsuc ...

How to resolve CORS error when using custom request header in Django with JavaScript and redirecting to OPTIONS request?

I am currently working on building an API library using Django. This API will be accessed by javascript, with the Django-API and javascript running on separate servers. The Django API library requires a custom request header from the javascript front end, ...

Pass an image into an input field with the attribute type="filename" using JavaScript directly

My goal is to automate the process of uploading images by passing files directly to an input type="filename" control element using JavaScript. This way, I can avoid manually clicking [browse] and searching for a file in the BROWSE FOR FILES dialog. The re ...

"Troubleshooting: Difficulty with hover function in jqgrid not functioning on colored rows

My JQGrid setup includes the following: <table id="grid"></table> var data = [[48803, "DSK1", "", "02200220", "OPEN"], [48769, "APPR", "", "77733337", "ENTERED"]]; $("#grid").jqGrid({ datatype: "local", height: 250, colNa ...

When implementing dynatable with Meteor, the outcomes may vary between the demonstration in a fiddle and the actual application

Here is the fiddle I created for this question: https://jsfiddle.net/ereday/82wzwem8/2/ In the fiddle, you'll notice that the table header has a green background. Now, let me share the code snippet from my meteor project: simple-todos.html <head ...

Shift the element within the div towards the left side

I am trying to create an animation for an element that moves to the left when hovered over, but the code I thought was correct doesn't seem to be working in my fiddle. Here is the link to the fiddle I created: https://jsfiddle.net/feb8rdwp/3/ Based ...

Parameterized query causing JavaScript error

As I struggle with this issue for more than a day now, a scenario unfolds where a user clicks on a link of a book name triggering me to read that book's name. Subsequently, an Ajax request is made to a Jersey resource within which a method in a POJO c ...

Exploring the Potential of jQuery through iBooks

Would like to know how to fix an issue with an interactive glossary I'm creating for an iBooks eBook. When clicking on a term, the definition should appear at the end of the page. Hiding the definition can be done by clicking on the term again or by c ...

Exploring the concept of next middle-ware within the realm of Express.js and Sail.js controllers

Currently, I am utilizing sails.js framework which is constructed on top of express.js. Within my routes.js file, I have defined a route as shown below: '/account/login': { controller : 'Session', action : 'l ...

Fetching form data using the .add method in PHP

I'm facing an issue where I upload a text/plain file and use jQuery AJAX to pass it to PHP for processing. However, the jQuery AJAX call is returning an error: jquery-2.2.3.js:8998 Uncaught TypeError: Illegal invocation https://i.sstatic.net/eFjYF.png ...

Leveraging the Google Feed API using jQuery's AJAX functionality

Currently, I am attempting to utilize Google's Feed API in order to load an RSS feed that returns a JSON string. (For more information, please refer to: https://developers.google.com/feed/). Despite this, my approach involves using jQuery's AJ ...

Guidelines for retrieving a file from Amazon S3 through a web browser utilizing Python (and boto) on Google App Engine

I have a Python program running on Google App Engine using boto 1.9b that retrieves all keys from an S3 Bucket and formats the output into an HTML table. bucket_instance = conn_s3.get_bucket(bucketname) liste_keys = bucket_instance.get_all_keys() table = ...

How you can fix the issue of the "Element not visible" error occurring specifically for one element within the popup

Error Message: "Element Not Visible" when Script Reaches Last Element Despite all attributes being in the same form, an error occurs when the script reaches the last element and displays "element not visible." All elements are enclosed in div tags on the ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

modifying the click state using a variable in jquery

Something feels off about my approach to this task. I currently have a series of hyperlinks, and when they are clicked, they go through a short sequence before changing states. When clicked again, they revert to their original state. var favourites = fun ...

executing a Prisma database migration with various schemas

I am currently immersed in a Prisma project where my goal is to create a node module that can be utilized by other projects. The challenge now is to ensure that the database stays synchronized with the models and the primary project, so all testing platfor ...

The div functions seem to stop working properly after they have been multiplied

Initially, I use JavaScript to multiply the div but then encounter issues with the function not working properly. function setDoorCount(count) { $('.doors').html(''); for (var i = 0; i < count; i++) { var content = " ...