-1

I have this menu on my home page.

<ul class="menu">
    <li><a class="active" href="index.html">Home</a></li>
    <li><a href="blog.html">Blog</a></li>
    <li><a href="#about">About</a></li>
    <li><a href="#contact">Contact</a></li>
</ul>

In my about page, the code is slightly different.

<ul class="menu">
    <li><a href="index.html">Home</a></li>
    <li><a class="active" href="blog.html">Blog</a></li>
    <li><a href="index.html#about">About</a></li>
    <li><a href="index.html#contact">Contact</a></li>
</ul>

Basically, when I click on one menu item, the active class is only added to the clicked one. That's easy.

The problem is that about and contact are not pages. They are sections of home page. When I'm in blog page, click on "About" link, it will move back to home page, to the place where the about is residing at. But the active is not added, because there's a page reload, my click event makes no changes. This is where I get stuck. It seems easy but I don't know how to do it at all...

I'm using jQuery so it's nicer if you guys help me with jQuery. Thanks.

Raw Ro
  • 11

2 Answers2

0

Try this code please

<ul class="menu">
    <li><a href="index.html" class="home">Home</a></li>
    <li><a class="active blog" href="blog.html">Blog</a></li>
    <li><a href="index.html#about" class="about">About</a></li>
    <li><a href="index.html#contact" class="contact">Contact</a></li>
</ul>

<script>
    $('.menu .about').click(function(){

        $('.home').removeClass('active');
        $('.blog').removeClass('active');
        $('.contact').removeClass('active');
        $('.about').addClass('active');

    });

    $('.menu .contact').click(function(){

        $('.home').removeClass('active');
        $('.blog').removeClass('active');
        $('.contact').addClass('active');
        $('.about').removeClass('active');

    });
</script>
Kamran Jabbar
  • 858
  • 7
  • 21
0

Since on click event isn't working - can't be working, when you are redirected from other page, you need to read the hash (e.g. index.html#contact) from the current url.

Based on your post I understand that you already added id-s to menu items like this:

<ul class="menu">
    <li><a id="home" class="active" href="index.html">Home</a></li>
    <li><a id="blog" href="blog.html">Blog</a></li>
    <li><a id="about" href="#about">About</a></li>
    <li><a id="contact" href="#contact">Contact</a></li>
</ul>

(I've added id-s to every menu link)

And then you need to use some more jQuery:

$(function() {
    var MenuSelected = location.hash.replace("#",""); //remove hash, so the variable can be directly used as id
    $("ul.menu li").removeClass("active"); // reset active element in case that some element is already set to active
    $("#" + MenuSelected).addClass("active");
});

You can also use this code for click on the same page, just use it inside

$("ul.menu li").click(function(){
   // JS code from above
});
Jan Vidic
  • 134
  • 9