Afplaktape
Afplaktape

Reputation: 13

Add active class after page load

I've been working on a custom menu in a wordpress website. This is why I can't use the standard worpress selector for active menu item. I want to add an active class to the active link. This is my html:

<div class="nav">
<ul id="menu">
 <li><a href="/item1">item1</a></li>
 <li><a href="/item2">item2</a></li>
 <li><a href="/item3">item3</a></li>
</ul>

Here is my jQuery:

 $(document).ready(function() {
        $('div.nav ul#menu li a').on('click', function(event) {
            $(this).addClass('active');
        });
    });

Everything works fine, it adds the class, but then the page is reloaded and the class is deleted. Is there a way to add the class to the active element when the page is refreshed? Thanks in advance!

Upvotes: 0

Views: 3553

Answers (2)

Anfath Hifans
Anfath Hifans

Reputation: 1598

try this,

<div class="nav">
    <ul id="menu">
        <li><a href="/item1" class="active">item1</a></li>
        <li><a href="/item2">item2</a></li>
        <li><a href="/item3">item3</a></li>
    </ul>
</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
document.onreadystatechange = function(){
    var selected_parent;
    if(document.readyState === 'interactive'){
        selected_parent = $('#menu').children().find('a').filter('.active').parent('li').index();
        jQuery.data( document.body, "selected_parent", selected_parent);       
    }
    if(document.readyState === 'complete'){ 
        var selected_parent = jQuery.data( document.body, "selected_parent" );
        $('#menu').children('li:eq('+selected_parent+')').children('a').addClass('active');
    }
}
</script>

Upvotes: 1

Mitya
Mitya

Reputation: 34608

Several ways. Store the info in localStorage or cookies, or append it to the URL via a hash.

Here's the hash approach. On click, we append the index of the clicked li to the hash, e.g. my_page.html#3.

$(function() {

    //grab menu and listen for clicks...
    var menu = $('div.nav ul#menu');
    menu.on('click', 'li a', function() {

        //...highlight, and log parent LI's index in URL hash
        $(this).addClass('active');
        location.hash = $(this).closest('li').index();
    });

    //onload, auto-highlight a previously-selected link? Trigger a click on it if so.
    var active_onload = location.hash.replace(/^#/, '');
    if (active_onload) menu.find('li:nth-child('+active_onload+') a').trigger('click');
});

Then, on DOM ready, we check the hash to see if we need to highlight the one that was previously selected.

This assumes hashes aren't used for internal links in the page. If they are, a localStorage approach (using the same principles, but storing in localStorage rather than URL hash) would be better.

Upvotes: 1

Related Questions