How to save the active link in the navigation list (twitter bootstrap)?

I would like to show the active link when the link is clicked (and this link will remain active as long as the user is on link 1) (I use Symfony2 with Twitter loading)

<ul class="nav nav-list"> <li class="active"> <a href="/link1">Link</a> </li> <li class=""> <a href="/link2">Link</a> </li> <li class=""> <a href="/link3">Link</a> </li> </ul> 

EDIT
The menu template is imported on each page as a block (I use a branch), for example, for link1.html.twig, I would:
{% include menu.html.twig%}

code html ...

etc.

Any help would be greatly appreciated.

+2
source share
3 answers

That should work :)

JQuery

 var x = $(location).attr('href').replace( 'http://yourdomain.com' , ""); // Step 1 $('a[href="' + x + '"]').addClass('active'); // Step 2 

Edit

Explanation

(Step 1). To a large extent, you capture the full URL and page name in the x variable "http://yourdomain.com/page.html", deleting the domain name "http://yourdomain.com" you with '/page.html'

(Step 2) Match the link that has the value '/page.html' and add the class 'active' to it

+3
source

I assume that each page has its own navigation elements. You just need to change which element has the "active" class.

Link1 is active since this is Link1.html:

 <ul class="nav nav-list"> <li class="active"> <a href="/link1">Link</a> </li> <li class=""> <a href="/link2">Link</a> </li> <li class=""> <a href="/link3">Link</a> </li> </ul> 

Link2 is active since this is Link2.html:

 <ul class="nav nav-list"> <li class=""> <a href="/link1">Link</a> </li> <li class="active"> <a href="/link2">Link</a> </li> <li class=""> <a href="/link3">Link</a> </li> </ul> 

If you are doing something more complicated than just going to a new page, refresh your question and explain how your question is a bit vague, otherwise it should work.

0
source

One way POCSS (Plain Ol 'CSS):

In your main.twig file

 <body class="{% block body_class 'home' %}"> <!-- stuff here --> <ul class="nav nav-list"> <li class="nav-home"> <a href="/">Link</a>Home</li> <li class="nav-about"> <a href="/about">About Us</a> </li> <li class="nav-contact"> <a href="/contact">Contact Us</a> </li> </ul> 

In the template about_page.twig

 {% block body_class 'page-about' %} 

In your CSS file

 .page-about .nav-about, .page-home .nav-home, .page-contact .nav-contact { /* Active styles here */ } 

The advantage of this is that you can set other things on your pages according to the setting of the body class, for example:

 .page-about a { h1: green; } .page-home a { h1: blue; } .page-contact a { h1 : pink; } 
0
source

Source: https://habr.com/ru/post/950736/


All Articles