Prevent Bootstrap scrollspy from adding URL hash
Asked Answered
M

1

7

I've implemented Bootstrap 3.0's scrollspy as follows:

<nav id="navProposalPreview">
    <ul class="nav navbar-nav">
        <li class="active"><a href="#previewTitlePage">Title Page</a></li>
        <li><a href="#previewDisplay">Display</a></li>
        <li><a href="#previewAddlServices">Additional Services</a></li>
    </ul>
</nav>
<div class="modal-body">
    <div>
        <p id="previewTitlePage"></p>
        <div>Stuff</div>
        <p id="previewDisplay"></p>
        <div>Other stuff</div>
        <p id="previewAddlServices"></p>
        <div>Last stuff</div>
    </div>
</div>

I'm initializing it like this:

$('.modal-body').scrollspy({ target: '#navProposalPreview', offset: 20 });

It sets the active li as expected as you scroll and also allows for navigating to sections using the links. The problem is that when you click on the links it will append the link to the URL in a hash eg. mysite.com/#previewDisplay. I don't want the URL to be changed at all.

I've run into this before in tabs I believe and I forget if the solution was to set the data-parent or add a click event like this:

$previewModal.find('#navProposalPreview a').on('click', function (e) {
    e.preventDefault();
    return false;
});

Adding data-parent isn't relative to scrollspy like it is for tabs and the click event above results in the link not navigating.

Thanks in advance.

Moya answered 10/6, 2014 at 16:14 Comment(2)
do you mean data-target did you try that adding data-targer="#Foolhardy
@nol: To what elements?Moya
F
5

ok here it goes via bootstrap

**"To keep URLs intact, use the data-target attribute instead of href="#"."**

like this

data-target="#"

http://getbootstrap.com/javascript/#dropdowns

here is a working fiddle example sorry for the confusion! data-target="#navbar" for on the container of where the anchor links to

Foolhardy answered 10/6, 2014 at 18:44 Comment(2)
Are you saying eg. my 2nd li should be <li><a data-target="#previewDisplay">Display</a></li>?Moya
That doesn't work plus the setting of the target is what I'm doing in my javascript (see original post).Moya

© 2022 - 2024 — McMap. All rights reserved.