Pergunta

I want to add an active class to the current <a> without href.
I have this language list:

<ol>
    <li>
        <a data-value="en">English</a>
    </li>
    <li>
        <a data-value="de">Deutsch</a>
    </li>
    <li>
        <a data-value="nl">Nederlands</a>
    </li>
</ol>

And this jquery:

a.click(function(event) {
    var url = location.href = "index.php?lang=" + $(this).attr("data-value");
location.href = url;    
});

I trying to add class active to <a> as the following:

a.removeClass('active');
    $(this).addClass('active');

But when i change language the page refresh and the .addClass doesn't work, so i tried to add class active based on URL (the url of pages is mysite.com/index.php?lang=en, mysite.com/index.php?lang=de, etc):

var href = jQuery(this).find('a').attr('href');
$('a[href="' + href + '"]').addClass('current');

but even this doesn't work!
I assume that the problem is caused from data-value, so how can I add active class to the current without href and add the class also after the refresh?

Foi útil?

Solução

You can determine the language from the current location and then use that to find the correct anchor:

var lang;

if (lang = location.href.match(/lang=([a-z]{2})/)) {
  $('[data-value=' + lang[1] + ']').addClass('active');
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top