Bootstrap scrollspy when accessing from another page

2.2k Views Asked by At

Im trying to link to a specific section of my home page while maintaining a scroll spy feature.

With this code:

<li><a href="#sec1">About</a></li>

the scrollspy is functioning but if I try to access it from a page other than my home page it just adds "#sec1" to the current page's url, to no effect.

If I change it to:

<li><a href="/#sec1">About</a></li>

It takes me to the correct section on the home page, but the scrollspy function no longer works.

js code

$(function(){/* smooth scrolling for scroll to top */
     /* highlight the top nav as scrolling occurs */
     $('body').scrollspy({ target: '#navbar' })
});

Any ideas?

2

There are 2 best solutions below

0
On

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

0
On

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();
    }
});