I
I
Ivan Malyshev2015-09-23 12:46:48
JavaScript
Ivan Malyshev, 2015-09-23 12:46:48

How to assign a class to the active menu link using js?

The point is this. I am making a site on WP, it became necessary to make a static menu, but when you go through the menu items, the active item should be highlighted.
On one of the projects, I already did this using the following script:

<script type="text/javascript">
$(function () { // Когда страница загрузится
$('.nav a').each(function () { // получаем все нужные нам ссылки
var location = window.location.href; // получаем адрес страницы
var link = this.href; // получаем адрес ссылки
if(location == link) { // при совпадении адреса ссылки и адреса окна
$(this).parent().addClass('active'); //добавляем класс
}
});
});
</script>

In this case, the li tag of the active link was assigned the class active. Here is the actual menu:
<ul class="nav navbar-nav">
 <li><a href="<?php bloginfo('url'); ?>/o-sayte">О сайте</a></li>
 <li><a href="<?php bloginfo('url'); ?>/reklama">Рекалама</a></li>
 <li><a href="<?php bloginfo('url'); ?>/vakansii">Вакансии</a></li>
 <li><a href="<?php bloginfo('url'); ?>/kontakty">Контакты</a></li>
 </ul>

I check alert(location); - the full link is displayed, as it should be, I check alert(link); - nothing is displayed.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_darkway, 2015-09-23
@hronik87

$('.navbar-nav li').click(function(){
$('.navbar-nav li').removeClass('active');
$(this).addClass('active');
});

D
Denis Ineshin, 2015-09-23
@IonDen

You are doing everything wrong.
The active menu item must be configured on the server side when you assemble the final page with your PHP. I'm sure that WordPress has such functionality out of the box and you just need to google a little.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question