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

Activate automatic click or force trigger JavaScript function

In the MVC view I am working with, there is a form that allows for file submission. //Submit file <% using (Html.BeginForm("MethodName","ControllerName", FormMethod.Post, new { enctype = "multipart/form-data"})) { %> <input type=" ...

Is there a way to improve scrolling speed on Mobile Safari?

I'm currently working on a project utilizing angularjs and bootstrap, aiming to replicate iOS's navigationController feature. However, I'm encountering speed issues, particularly when scrolling between views on mobile safari iOS. The transi ...

Emotion, material-ui, and typescript may lead to excessively deep type instantiation that could potentially be infinite

I encountered an issue when styling a component imported from the Material-UI library using the styled API (@emotion/styled). Error:(19, 5) TS2589: Type instantiation is excessively deep and possibly infinite. Despite attempting to downgrade to typescript ...

How to efficiently monitor and calculate changes in an array of objects using Vue?

I have a collection named people that holds data in the form of objects: Previous Data [ {id: 0, name: 'Bob', age: 27}, {id: 1, name: 'Frank', age: 32}, {id: 2, name: 'Joe', age: 38} ] This data can be modified: New ...

Is there a way to utilize OpenLayers to showcase various icons for distinct features all within one layer?

Being new to Openlayers/JS and fairly inexperienced with programming in general, there may be other issues in my code that I'm unaware of. I am currently using the latest version of Openlayers (5.3.0). My application sends GeoJson formatted data via ...

Calculate the mean value of each array, and then determine which average is higher

After running the code snippet provided, I noticed that it outputs "first" instead of "second". Can you help me verify my logic here? I first calculate both averages and then compare them to return the greater one. Do you see any issues with this approac ...

Loading elements of a webpage in a consecutive order

I am currently working on implementing a content slider within my Django application. The specific slider that I am using can be found at this link. One challenge that I am facing is the need to load close to one hundred 'contentDiv' pages, and I ...

The functionality of two-way binding in a distinct controller is not functioning properly when integrated with angular-wizard

I've been working hard to integrate this amazing wizard controller into my project: However, I've hit a roadblock with two-way binding not functioning as expected outside of the <section> attribute: http://plnkr.co/edit/N2lFrBRmRqPkHhUBfn ...

Error: The Vuex store is not defined in the Vue.js component when attempting to access it using

I've recently set up a new vue-cli webpack project with Vuex. I have initialized my Vuex store in store.js like so: import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); const store = new Vuex.Store({ state: {} }); export default store; ...

Use the `fetch` method in JavaScript/TypeScript to make an API call to an IPFS URI but be prepared for potential issues like CORS restrictions, network errors, or

I am currently working on a Next.js project with TypeScript in the browser, and I need to execute the following fetch request: const tokenURIResponse = await fetch( "ipfs://bafybeig37ioir76s7mg5oobetncojcm3c3hxasyd4rvid4jqhy4gkaheg ...

I'm curious about why I'm receiving the error "Unable to bind to 'ngFor' since it is not recognized as a property of 'li'. Can someone please explain why this is happening?

The issue is related to the *ngFor directive for nonvegfoodlist app.component.ts import { Component } from '@angular/core'; export class Menu { id : number; name :string; } const veg : Menu[] = [ { id:1 , name:'Rice'}, { id: ...

Exploring the integration of external javascript AMD Modules within Angular2 CLI

During my experience with Angular2 pre-releases, I found myself using systemjs to incorporate external JavaScript libraries like the ESRI ArcGIS JavaScript API, which operates on AMD modules (although typings are available). Now that I am looking to trans ...

Creating an Android application that integrates HTML styling efficiently

I currently have a social networking site with a mobile web version, and my goal is to package that view into an Android app and potentially enhance it with a custom splash screen. Essentially creating a branded browser window. If you have any tips or adv ...

Insert Angular HTML tag into TypeScript

I am currently working on creating my own text editor, but I'm facing an issue. When I apply the bold style, all of the text becomes bold. How can I make it so that only the text I select becomes bold without affecting the rest of the text? Additional ...

Incorporate the key as a prop within a Child Component in a React application

I am trying to display a list of elements in React, where the key of each element is used as an index in front of the item. However, when I try to access props.key, it just returns undefined. Does anyone have any suggestions on how to access the key proper ...

Enhanced efficiency in the interaction between front-end JavaScript and back-end JavaScript

As a frontend developer, I find myself in the unique position of working on a project that involves processing a large amount of data in my nodeJS backend (while using reactJS for the front end). After the necessary data processing is completed in the bac ...

Refresh the div by clicking it

$(window).load(function() { $("#Button").click(function() { alert('clicked') $("#div").load(" #div > *"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script ...

DIV size issue resolved

Content within a div is surpassing the set fixed size determined by CSS. <style> #fixeddiv { position: fixed; margin: auto; max-height: 300px; max-width: 700px; } </style> <div id="fixeddiv"> <div id="M77 ...

React does not recognize data.map as a function

Currently, I am facing an issue with a simple map function in React that is supposed to create a set amount of times. {times.map((time) => ( <Pill value={time} handleTimes={handleTimes} key={time} /> ))} The error being thrown i ...

Ways to customize the appearance of an iframe's content from a separate domain

I am facing a challenge with my widget and multiple websites. The widget is hosted on one domain, but the websites use an iframe to display it. Unfortunately, because of the Same Origin Policy, I cannot style the content of the iframe from the parent websi ...