Marks Gniteckis
Marks Gniteckis

Reputation: 473

Switch <li> active element

Here is a link for a fiddle project I am working on right now. What I am trying to do is to switch active menu element depending on what section is displayed right now on screen. So if it is Kontakti on screen, then Kontakti in menu (<!--NAV BAR-->) has to display as active item. I am not familiar with jS

Upvotes: 1

Views: 301

Answers (3)

Hemant
Hemant

Reputation: 2059

Add data-role=navigate attribute to ul element where navigation is housed, In the javascript section of this fiddle,

please try with the following code,

 $(function()
  {
  $("[data-role=navigate]").find("li > a").click(function()
    {
        $(this).parents("ul").find("li.active").removeClass("active");
        $(this).parent().addClass("active");
    })

  })

I will explain in brief what the code does...

1) Binds a click event handler to <a> inside <li> which is inside <ul> with attribute data-role=navigate

2) When the click happens, it removes the active class for the current element.

3) Assigns the active class to the immediate parent of the <a>

It is a good practice to target specific needs in JS by placing attribute in the DOM elements and hooking up event listeners using that attribute.

Hope it helps!

Upvotes: 2

jyrkim
jyrkim

Reputation: 2869

Bootstrap's Affix might be something that could be useful in this case. It highlights what part of the page is displayed on the screen on a separate sub-navigation part of the page.

Btw, if you have Bootstrap code you can display it on Bootply quite easily. It provides Bootstrap's CSS and JavaScript files by default.

Upvotes: 2

imjared
imjared

Reputation: 20554

You say you're not familiar with JavaScript but you're asking for functionality that needs JavaScript. I'd recommend trying to use a plugin if it's not something you can write yourself.

Waypoints would do exactly what you're looking for: http://imakewebthings.com/waypoints/guides/getting-started/

Upvotes: 1

Related Questions