0

i am trying to create a navigation menu as shown below. how do i get my javascript to change the color of selected anchor tag menu.

HTML

<script type="text/javascript">
$(function() {
       $("#menu ul li a").click(function() {
       // remove classes from all
       $("#menu ul li a").removeClass("active");
       // add class to the one we clicked
       $(this).addClass("active");
      });
   });
</script>

<div id="menu">
   <ul>
        <li><a href="index.html" class="active">home</a></li>
        <li><a href="about.html">about</a></li>
        <li><a href="portfolio.html">portfolio</a></li>
        <li><a href="contact.html">contact</a></li>
    </ul>
</div>

CSS

#menu ul li a{background: -webkit-gradient(linear, left top, left bottom, from(#c5c5c5), to(#fff));;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;}

#menu ul li a:hover {
    background: -webkit-linear-gradient(top, #009ec5 0%, #005890 50%, #41d2fc 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
    }

#menu ul li a.active {
    background: -webkit-linear-gradient(top, #009ec5 0%, #005890 50%, #41d2fc 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
3
  • 2
    It sounds like you just want this CSS: .active { color: red; } Mar 29, 2014 at 12:52
  • it'll depend on the CMS you are using if any that or compare the url to the current item...
    – vimes1984
    Mar 29, 2014 at 12:52
  • You're problem is that you want to execute some javascript while the browser is loading a other page. So you can change the class but the page is reloaded so there is no active class anymore on the clicked item. Mar 29, 2014 at 12:56

2 Answers 2

2
$('#menu ul li a').click(function(){

    $('#menu ul li a').removeClass('active');
    $(this).addClass('active');
});
1

By the looks of it you aren't preventing going to a new page when your anchors are clicked. So I'm assuming that you'd just like to apply the class to the link corresponding to the page your currently on.

You don't need a click() event handler for this. You need to use the window.location.href to determine which page it is your on. Remove the class from the default link and then add it to that with a href attribute matching the window's href. Something like the following will do:

$(function() {
    var page = window.location.href.split('/');
    page = page[page.length-1];
    $("#menu ul li a").removeClass("active").filter('[href="'+page+'"]').addClass('active');
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.