S
S
Sol-Mayers2020-01-19 00:26:35
JavaScript
Sol-Mayers, 2020-01-19 00:26:35

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

1 answer(s)
E
EvgeniySaschenko, 2020-01-19
@EvgeniySaschenko

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 question

Ask a Question

731 491 924 answers to any question