Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlight current menu item in sidebar

I'm using django with Twitter Bootstrap. My current view resembles one of the examples provided. Looking at the example, one can imagine the user clicking one of the links in the sidebar to see different views, each framed with this same sidebar. One would imagine that the link selected would then be highlighted just like the example using the code:

<li class="active"><a href="/sample/link/here/">Link</a></li>

The active class needs to be attached to the correct menu item. How might I assign this "active" class to the correct menu item? Originally, I tried using a variable from my view to assign it with jquery:

$(document).ready(function() {
    $("#{{ current_view }}_nav").addClass('active');
});

<li id="linkone_nav"><a href="/sample/link/here/">Link</a></li>

This seems cumbersome though. It requires that I pass the id to the template from the view. Lots of ids to manage as well. Is there a better / more preferred way to assign this active class?

like image 413
Ed. Avatar asked Aug 16 '12 15:08

Ed.


People also ask

How do I highlight the current menu in WordPress?

Below are the steps to add a CSS class to the menu and highlight it using a custom CSS. Step 1 – From the WordPress dashboard navigate to Appearance > Menus. Step 2 – Click on Screen Options and tick the CSS Classes checkbox. Step 3 – Click on the menu item that needs to be highlighted.

Which event are used to highlight the menu items?

Each time a menu is selected, mouse or keyboard, the Paint event is raised.


1 Answers

I think your use of # for the href in your sample code is clouding the issue. I'm assuming your real-world scenario is actual real links and automatically highlighting them based on the active URL. If that's correct, then just do:

{% url something as url %}
<li{% if request.path == url %} class="active"{% endif %}><a href="{{ url }}">Link1</a></li>

Where, "something" is the name of a urlpattern or dotted-path to a view, etc. This assumes you're reversing the URL, obviously, so if you're using a static URL, you'd just hardcode it:

<li{% if request.path == "/my/full/url/path/" %} class="active"{% endif %}><a href="/my/full/url/path/">Link1</a></li>
like image 153
Chris Pratt Avatar answered Sep 24 '22 07:09

Chris Pratt