skip to Main Content

I am aware of the below function, which will scroll to a defined element when a page is loaded:

$(document).ready(function () {
    // Handler for .ready() called.
    $('html, body').animate({
        scrollTop: $('[class-name]').offset().top
    }, 'slow');
});

However, I would like this function to run only when the page is accessed by the <a class="[class-name]" href="[destination-url]" </a> currently in a banner on the home page, which is there temporarily to bring attention to some information on the destination page.

I don’t want this function to run when the same page is accessed via the main sidebar menu, or other links.

How would I go about this?

2

Answers


  1. When you want an element to be slow-scrolled to when navigated to from another page, change those links on the other page to add a search parameter. For example, instead of the link ending in example.html, make it end in example.html?scrollto=foo. Then, on the destination page, see if the scrollto exists, and if it does, scroll to an element with that class.

    const params = new URLSearchParams(window.location.search);
    const paramsObj = Object.fromEntries(params.entries());
    if (paramsObj.scrollto) {
        $('html, body').animate({
            scrollTop: $('.' + paramsObj.scrollto).offset().top
        }, 'slow');
    }
    
    Login or Signup to reply.
  2. It’s simple,
    below assumption taken that you want to implement this code in
    below link

    https://example.com/xyz.html?scroll=true

    so here code be like this.

     if(window.location.href.includes('scroll=true')
           {
            $('html, body').animate({
                  scrollTop: $('[class-name]').offset().top
             }, 'slow');
       }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search