Richlewis
Richlewis

Reputation: 15374

Adding class to li on click

I must be missing something here as I thought that this would work.I have a navbar and upon clicking links you navigate to through the site, simple enough.. So when i click on an anchor tag i would like that li to have a class name assigned to it, basically adding some styling the link so the user can identify which page they are on

Navbar

 <ul id="main-menu" class="clearfix">
    <li>
      <%= link_to '<i class="icon-home"></i> Home'.html_safe, root_path %>
    </li>

    <li>
      <%= link_to '<i class="icon-desktop"></i> About Me'.html_safe, pages_aboutme_path %>
   </li>

    <li>
      <%= link_to '<i class="icon-picture"></i>  Portfolio'.html_safe, pages_portfolio_path %>
    </li>

    <li>
      <%= link_to '<i class="icon-comments"></i> Blog'.html_safe, blog_path %>
    </li>

    <li>
      <%= link_to '<i class="icon-envelope"></i> Contact'.html_safe, contact_path %>
    </li>
  </ul>

My jquery attempt

$('#main-menu > li > a').click(function() {
  $(this).parent('li').addClass('current-menu-item');
});

Am i correct in thinking that its the rendering of the new page that is causing an issue here?

Any pointers appreciated

Upvotes: 1

Views: 120

Answers (3)

achudars
achudars

Reputation: 1506

jQuery('a').click(function () {
    jQuery(this).parent().addClass('current-menu-item');
});

jsFiddle

Upvotes: 0

Bernhard
Bernhard

Reputation: 8821

Yes, when you don't prevent the default action of the link and the click navigates away from the current page, the added class will be lost on the newly loaded page.

Upvotes: 1

MDEV
MDEV

Reputation: 10838

When the link is clicked the page is changing, which means all the HTML is re-loaded - clearing any added CSS classes before you've even noticed them. You're better off using server side script to work out which page is active and sending the HTML with the active class already on the li

Upvotes: 7

Related Questions