jQuery how do use `addClass` on a list item

112 views Asked by At

I am trying to add a class to my li element which contains nav links and it works perfectly when using a null hrefs but as soon as I actually add links it stops working.

$(document).ready( function () {
      $('#menu li').click(function() {
            $('li.selected').removeClass('selected');
            $(this).addClass('selected');
     });
 });

<ul id="menu">
                <li class="menu-item selected"><a href="#">Home</a></li>
                <li class="menu-item "><a href="#">History</a></li>
                <li class="menu-item "><a href="#">Language</a></li>
</ul>

As soon as I change the null href (#) to home.html , history.html & language.html the class is not added.

I reckon this is because it loses the first click event (addclass) when the link is actually clicked.

How do I get the li class to stay when the link is clicked?

1

There are 1 answers

2
Nikhil Aggarwal On

This will not work. You need to update your strategy in order to make it working.

In place of href and data-href attribute. Please note, it can be any data other attribute as well

<li class="menu-item selected"><a data-href="home.html" href="javascript:void(0);">Home</a></li>

Now, update your javascript.

$('#menu li').click(function() {
            $('li.selected').removeClass('selected');
            $(this).addClass('selected');
            var dataHref = $($(this).find("a")[0]).attr('data-href');
            if (dataHref !== undefined) {
                window.location.href = dataHref;
            }
     });

Explaination

We have the binding of li element containing anchor element. What happens is when we click the li, most likely you are going to click the anchor.

Hence, the anchor clicks executes first and then event bubbles to the li whose click is triggered. But by the time click reaches li, things have changed in the HTML, hence, things not working as desired.

So, what we have to do is remove, the href of anchor. And let the click be binded to li element.

So, when li is clicked, it does the HTML manipulation and then checks, whether there is any anchor in the li. If yes, then check if that anchor has any data-href attribute. If that anchor has data-href attribute, change the window.location.href to that href.

I hope it works for you!!