E
E
Enter_a_nickname2022-04-20 17:53:14
JavaScript
Enter_a_nickname, 2022-04-20 17:53:14

Why can't I assign the current class to a menu item?

my html:

<aside>
        <div class="menu">
            <a href="{% url 'home' %}" class="home">
                <img class="home-img" src="{% static 'main/img/home.svg' %}">
                <span class="navigation_label">Home</span>
            </a><br>
            <a href="{% url 'orders' %}" class="orders">
                <img class="orders-img" src="{% static 'main/img/orders.svg' %}">
                <span class="navigation_label">Orders</span>
            </a><br>
            <a href="{% url 'account' %}" class="Account">
                <span class="navigation_label">Account</span>
            </a><br>
        </div>
    </aside>


In that case my jquery looks like this?
let url = location.href;

  if (url.slice(-1) == '/') url = url.slice(0, -1);
  $($('#menu a').children().get().reverse()).each(function() {
    let link = $(this).children('a').first().attr('href');
    if (link.slice(-1) == '/') link = link.slice(0, -1);

    if (link && url.indexOf(link) === 0) {
      $(this).addClass('current');

      self.current = true;
    }
  });


Where did you go wrong? adding in css does not change anything:
.current{
  background: red;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Senbonzakuraa, 2022-04-20
@Enter_a_nickname

const itemMenu = $('#menu a');
const url = location.pathname;
itemMenu.each(function (el) {
  if($(this).attr('href') === url) {
    $(this).addClass('current')
  }
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question