Skip to content Skip to sidebar Skip to footer

Bootstrap Scrollspy When Accessing From Another Page

Im trying to link to a specific section of my home page while maintaining a scroll spy feature. With this code:
  • About
  • the scr

    Solution 1:

    you can try

    $(document).ready(function(){
        var href = window.location.href; 
        var splitit = (href.split('#'))[1]; //split url to get sec1 name
        if(splitit !== "" || splitit !== "undefined"){
            $('html, body').animate({
                scrollTop: $('#'+splitit).offset().top
            }, 2000);
        }
    });
    

    this code will split the url to get sec1 or sec2 .... and then scroll to the div with id="sec1"

    I mean if you redirect another page to www.website.com/anything#sec1 it will scroll the page to the div with id="sec1"

    take a look at this DEMO

    you can see this Jsffidle


    Solution 2:

    An alternative to the answer by @Mohamed-Yousef is to simulate the click on the links by doing

    $(document).ready(function() {
        // workaround for deep link via anchor
        var stripped_url = window
                        .location
                        .toString()
                        .split("#");
        if (stripped_url.length > 1) {
            var activeId = "#nav-deep-" + stripped_url[1];
            $(activeId)[0].click();
        }
    });
    

    The jQuery selector requires the appropriate id on the link element like <a id="nav-deep-sec1" href="#sec1">About</a>.

    And an even more elegant solution which avoids the extra IDs is to select the first link which points to the anchor by doing

    $(document).ready(function() {
        // workaround for deep link via anchor
        var stripped_url = window
                        .location
                        .toString()
                        .split("#");
        if (stripped_url.length > 1) {
            $("a[href='#"+stripped_url[1]+"']")[0].click();
        }
    });
    

    Post a Comment for "Bootstrap Scrollspy When Accessing From Another Page"