Use url and hash with scrollspy bootstrap

I have a twitter bootstrap-based navigation menu bar that I want to apply scrollspy for hightlighting. I include the menu on several pages using the usual php include. so I attach to the files using their file name plus a bookmark (e.g. products.php # foo).

but the way scrollspy wants to work with URLs is to use the <a href="#id-of-target">my link</a> format, so that when <div id="id-of-target"> scrolls in the view, href is mapped based on the href attribute and gets the active class placed in it.

which means that if I have a link like <a href="products.php#my-catalogue">my catalogue</a> , then it will not match the identifier, and the link will not stand out.

I could not figure out how to change scrollspy so that it matches only the identifier after # in the href value.

+2
twitter bootstrap
source share
2 answers

New answer

(1) You can add the target to your link:

 <a href="products.php#my-catalogue" data-target="#my-catalogue">my catalogue</a> 

(2) Bootstrap uses your href or data-target in your navigation links to find the target regions on the page. If you have something like products.php#my-catalogue , checking the correct expression in the code will fail. But if you crop in advance, it will work

In the spyware bootstrap scroll code, you can change (in the Refresh function in ScrollSpy):

 .map(function () { var $el = $(this) , href = $el.data('target') || $el.attr('href') , $href = /^#\w/.test(href) && $(href) 

to

 .map(function () { var $el = $(this) , href = $el.data('target') || $el.attr('href') , trimmed = href.match(/#\w*/)[0] , $href = /^#\w/.test(trimmed) && $(trimmed) 

and then having something like

 <a href="products.php#my-catalogue">my catalogue</a> 

no problem


Old answer

Perhaps you could try editing the scroll scroll selector in jst bootstrap code?

There is a line (about 1442 for me):

 selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' 

If changed to

  selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="products.php' + target + '"]' 

Can solve your problem

+13
source share

Adding data-target = "# target" works great. I use it on service sub pages. Here is a working example:

http://calebserna.com/services/web-design/

Visitors can easily view a list of services that link to another page.

+2
source share

All Articles