Guide on achieving a seamless scrolling effect to an identifier following the selection of a hyperlink from a different webpage

Imagine you have a link on a webpage,

<a href="https://example.com/#sample"><p>Click Me</a>

When you click on that link, it immediately jumps to the specified id on the page. But what if instead of this abrupt jump, you want the page to smoothly scroll from the top to the id?

Another issue arises when there is a sticky menu overlapping the target id after the jump, adding more importance to the smooth scrolling solution.

If coding in jQuery isn't your forte, seeking help for this functionality may be necessary.

EDIT The initial wording might've caused confusion. The actual scenario involves a link on one page leading to an id on another page:

Let's say the Homepage contains the following link:

<a href="https://example.com/anotherPage/#sample"><p>Click Me</a>

The desired smooth-scrolling effect should take place on the "anotherPage," where the target id resides.

Your understanding of the requirement has been key in finding a suitable solution. Thank you to everyone offering their assistance.

Answer №1

With just a few lines of jQuery, smooth scrolling to elements with anchors is made easy.

Simply use $('a[href*=\\#]') to target all anchor tags (<a>) with a hash symbol (#).

$(document).ready(function() {
    $('a[href*=\\#]').on('click', function(e){
        e.preventDefault();
        $('html, body').animate({
            scrollTop : $(this.hash).offset().top
        }, 500);
    });
});

Update

If you want to implement smooth scrolling on a new page, include the following code within that page:

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

This code will check for a hash in the URL and smoothly scroll to the element with the corresponding id.


Note 1: You can adjust the animation speed by modifying the 500 parameter which represents the time in milliseconds.

Note 2: Additionally, you can specify an easing type after the speed parameter. The default is swing (similar to CSS's ease-in-out), but you can change it to linear or another option of your choice.

Answer №2

To achieve smooth scrolling, you can utilize jQuery's animate function.

For a detailed example, refer to the following link on the w3 schools website: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll

$(document).ready(function(){
  // Implementing smooth scrolling for all links
  $("a").on('click', function(event) {

    if (this.hash !== "") {
      event.preventDefault();

      var hash = this.hash;

      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        window.location.hash = hash;
      });
    } 
  });
});

Answer №3

When it comes to linking to external sources, I have always relied on the following code snippet:

$(document).on("ready", function () {
      var urlHash = window.location.href.split("#")[1];
      $('html,body').animate({
          scrollTop: $('.' + urlHash + ', #' + urlHash +',[name='+urlHash+']').first().offset().top -100
      }, 1000);
  });

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

Feeling lost when it comes to forms and hitting that submit button?

Below is a sample form structure: <html> <head> <title>My Page</title> </head> <body> <form name="myform" action="http://www.abcdefg.com/my.cgi" method="POST"> <div align="center"> <br><br; <br& ...

No response text returned from the local Ajax request

Currently, I am facing a challenge while attempting to send an ajax call from the client to my server containing data related to an input parameter. The issue is that although I can view the data in my server's console, it does not display in the brow ...

Dynamic manipulation of classes based on user attributes

One thing I've noticed is that certain WordPress themes, like 'Thematic', include user-specific classes in the body element to avoid using CSS browser hacks. For example: wordpress y2010 m02 d26 h05 home singular slug-home page pageid-94 pa ...

What's causing this failed request in jQuery Deferred to unexpectedly resolve?

Trying to handle two AJAX deferreds, with a success message if both succeed and an error message if one fails. Check out the simplified code: var reqs = $.map(['file', 'db'], function(mode) { $.get(wspath(desyn.repo_id, 'rever ...

Verify if the username and password align by utilizing ajax in codeigniter

In the midst of my current project, I'm faced with a challenge involving a login modal. So far, I've managed to utilize AJAX for three key purposes: 1) Validating that both the username and password fields contain values; 2) Ensuring only the use ...

Is Flash compatible with Cache-Control & Expires headers across all web browsers?

Working on a Flash .swf file created by someone else without access to the source code can be a challenging task. It appears to have been developed in Flash 9/AS3, but the certainty is lacking. The configuration settings for this Flash file are loaded fro ...

When a POST request fails, which AJAX event is triggered?

How can you handle a failed post request in jQuery AJAX? Suppose the site shows this message: POST http://s-t-h-c.appspot.com/dispatch 500 (Internal Server Error) which AJAX event should you use to address it? In case of a successful request, we typicall ...

What is the best way to create a table using a for loop?

This is how the looping looks: for(var i=0;i < data.length; i++) { new_array.push(data[i].catalog_name,data[i].price); for (var j=0;j < new_array.length; j++){ $("#print_receipt").append("<table><tr><th>Item Name< ...

Function for jQuery Slide Toggle is not being invoked

I'm struggling with jQuery Slide Toggle. $(document).ready(function() { $("a").click(function() { $(this).parent().parent().children("p").Toggle(400); return false; }); }); I have multiple posts displayed on the page fetched from ...

Passing data to an iframe through Ajax request

I have been devoting my time to a special project, and I can proudly say that I am almost done with it. However, the hurdle I am facing right now revolves around the concept of *sending parameter to iframe*. My primary objective is to craft a basic editor ...

The HTML page is not responsive to the screen size of the mobile device

Check out my HTML code: <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Test</title> <style type= ...

What mobile browsers are compatible with the <track> element for html5 video playback?

Seeking information about web browsers that currently support the <video> tag. Are there any alternative solutions available? Can this tag be used on mobile phones, or would the text be too small to read? It seems more suitable for tablets with large ...

The carousel in the Project file seems to be malfunctioning

Having previously utilized Owl carousel on my website, I made the switch to slick carousel for the slider on a NATA coaching center in Chennai. Unfortunately, I'm encountering issues with getting the slider to work and I'm unsure of where I may b ...

Problem with a dropdown menu within a dynamically generated table in an HTML/PHP file

I've been experimenting with creating a drop-down table row below another one within a semi auto-generated table. After some research, I discovered that directly animating table elements is not possible. However, when I wrapped my table in a div, the ...

Exploring the differences between the meta viewport and font size

My website includes the following code in the section: <meta name="viewport" content="width=990"/> This setting helps to display my webpage well on mobile devices, as using width=device-width causes issues with elements that have 100% width. Howeve ...

Guide for positioning all navbar items except one to the left, beginning at the left edge, utilizing a set minimum and maximum width, while moving the final item to the right edge

Is there a way to align all items in a navbar except for one to the left, with a fixed combined minimum and maximum width of 300px-400px, while sending the last item to the right margin? I want the final result to resemble this: https://i.stack.imgur.com ...

After we close the overlay, the YouTube video continues playing without interruption

In my current project, I am facing an issue with opening a YouTube video in a jQuery Model Window. The problem arises when I close the overlay in IE, Safari, and Chrome; the YouTube video continues to play in the background, causing disruptions with other ...

Even if there is no overflow, the scroll bar will always be visible with the

I'm currently working on a project titled "Scrolling JQuery Mobile Panel Apart from Content", and you can check out my progress here. In order to achieve what I want, I have applied the following CSS code. However, I am facing an issue where the over ...

Angular not firing slide.bs.carousel or slid.bs.carousel event for Bootstrap carousel

I've searched high and low with no success. I'm attempting to detect when the carousel transitions to a new slide, whether it's automatically or by user click. Despite my numerous attempts, I have been unable to make this event trigger. I ha ...

Ensuring Consistent Visual Harmony Across Linked Elements

As part of my project developing an iPad app with PhoneGap and jQuery Mobile, I am looking to incorporate a preview pane within a carousel. This preview pane should display smaller versions of the other panes scaled inside it. The panes are dynamic and upd ...