kentor
kentor

Reputation: 18504

Change class of li element using Jquery

I have a navigation which highlights the currently selected navigation point by using the class active. When a user visits a new navigation point, i want to toggle of the "old" selected navigation point and toggle the class of the li element of the new navigation point to "active".

I have problems with the jquery part, which only should change toggle of the li class of the old element and adds the class to the clicked li element. Probably a standard situation, but I don't know a good and easy solution for this.

Example (before click):

<ul class="x-navigation">
<li class="active">
    <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard</span></a>                        
</li>
<li>
    <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard2</span></a>                        
</li>
</ul>

Result (after click on "Dashboard2"):

<ul class="x-navigation">
<li>
   <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard</span></a>                        
</li>
<li class="active">
  <a href="index.php"><span class="fa fa-desktop"></span> <span class="xn-text">Dashboard2</span></a>                        
</li>
</ul>

My try

$(".x-navigation li").on("click", "a", function(){
        event.preventDefault();
        //alert("test");

        ($this).parent().removeClass("active");
        ($this).addClass("active");

        //alert($this.child().href);
});

Error description:

Uncaught ReferenceError: $this is not defined at this row: "($this).parent().removeClass("active");

Shouldn't be $this the li element which got clicked ? I hope you guys can help me with such a standard problem.

Upvotes: 4

Views: 8435

Answers (2)

Ashenvale
Ashenvale

Reputation: 111

your question is telling me you want to toggle the class of the li element of the new navigation point to "active" , meaning you want the class "active" to be placed on the li of the link you just clicked.

but what your doing here is

($this).addClass("active");

is that your adding the class active to your anchor element instead because of this

$(".x-navigation li").on("click", "a", function(){

also this part :

($this).parent().removeClass("active");

should be like this, place the $ outside of (this):

$(this).parent().removeClass("active");

now if you really want to toggle it you can simple do this:

$(".x-navigation li").on("click", "a", function(){
  event.preventDefault();
  $(this).parent().addClass("active").siblings().removeClass("active");
});

Upvotes: 2

Jared Smith
Jared Smith

Reputation: 21926

The $ goes outside the parens. The dollar sign is the jQuery constructor call that your are providing this to as an argument:

$(this).parent()

and so on.

Upvotes: 5

Related Questions