Reputation: 2039
Update 1: JSFIDDLE http://jsfiddle.net/xz4xsc2r/1/
I created a website using bootstrap and scroll-spy in order to move around the page and make the navbar change depending on which section you are reading. The website has 2 pages. The first one is where the scroll-spy is used. The second one contains some other important information.
My navbar has 4 links, 3 are links to anchors in the samepage, while 1 is a link to the other page. Code:
<div id="scroll-spy-target" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#first">Início</a></li>
<li><a href="#ss-produtos">Produtos</a></li>
<li><a href="#ss-equipe">Equipe</a></li>
<li><a href="#ss-contato">Contato</a></li>
<li><a href="page2.html">Curvas</a></li>
</ul>
</div>
Problem: when I click on Curvas
, nothing happens. I am not redirected to the page2.html
.
Question: If I remove the id="scroll-spy-target"
then everything works, but I loose the functionality of scrollspy. How do I keep scroll-spy and make that link work?
Thanks a lot for helping!!!
Upvotes: 1
Views: 2279
Reputation: 2039
The problem occurred because I was using a function to smooth the scrolling when an anchor was clicked. The javascript function was:
$("#scroll-spy-target a").click(function(e) {
e.preventDefault();
var pageRef = $(this).attr("href");
var pageRefPosition = $(pageRef).offset().top ;
$("html,body").animate({
scrollTop:pageRefPosition
},400);
});
Which took the href
attribute from the clicked anchor <a>
, calculated its offset and scrolled the page (in 400 milliseconds).
The problem then occurred because my link was store inside an <a>
tag, so instead of loading the page, it tried to scroll to the link, so nothing happened.
The solution was to change load the page if it found a link inside the <a>
tag:
$("#scroll-spy-target a").click(function(e) {
e.preventDefault();
var pageRef = $(this).attr("href");
if(pageRef[0] != '#') {
window.location.href = pageRef;
} else {
var pageRefPosition = $(pageRef).offset().top ;
$("html,body").animate({
scrollTop:pageRefPosition
},400);
}
});
Because anchors always start with #
, anything else must be a link (hypothesis).
Upvotes: 1
Reputation: 521
From the boostrap website. add the data-spy and data-target to your body tag where the data-target is the class of your navbar. For example:
<body data-spy="scroll" data-target=".navbar-fixed-top">
<nav class="navbar navbar-inverse navbar-fixed-top">
Upvotes: 0