Answer the question
In order to leave comments, you need to log in
How to highlight the current menu item in pure js?
Goodnight. The task is the following - it is necessary to make a selection of the current menu item using pure js. So that the current page is underlined from the bottom. At the moment, the problem is that the selection only works on the first menu item, that is, on the main page. Selection does not work on other menu items. What could be the problem?
Here is the code:
<ul class="menu__list-desktop">
<li>
<a href="index.html" class="item__link--desktop">
<img src="img/logo-pink-white-desktop.svg" alt="main-logo">
</a>
</li>
<li>
<a href="index.html" class="item__link desktop-link">Главная</a>
</li>
<li>
<a href="photo.html" class="item__link desktop-link">Фотографии</a>
</li>
<li>
<a href="form.html" class="item__link desktop-link">Конкурс</a>
</li>
</ul>
.active-desktop-link {
border-bottom: 2px solid #ffffff;
}
document.querySelectorAll('.desktop-link').forEach(function(el) {
if ( window.location.pathname.indexOf(el.getAttribute('href')) > -1 ) {
el.classList.add('active-desktop-link');
}
});
Answer the question
In order to leave comments, you need to log in
Add data-id-page="page_id" to the body tag Add data-id-nav="page_id"
to the
navigation element
<body data-id-page="photo">
<ul class="menu__list-desktop">
<li>
<a href="index.html" class="item__link--desktop">
<img src="img/logo-pink-white-desktop.svg" alt="main-logo">
</a>
</li>
<li>
<a href="index.html" class="item__link desktop-link" data-id-nav="index">Главная</a>
</li>
<li>
<a href="photo.html" class="item__link desktop-link" data-id-nav="photo">Фотографии</a>
</li>
<li>
<a href="form.html" class="item__link desktop-link" data-id-nav="form">Конкурс</a>
</li>
</ul>
</body>
let pageId = document.querySelector("[data-id-page]").getAttribute("data-id-page"),
navItem = document.querySelector(`[data-id-nav=${pageId}]`);
if(pageId == navItem.getAttribute("data-id-nav")) {
navItem.classList.add("active-desktop-link");
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question