Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 252
kentor Avatar asked Mar 17 '23 21:03

kentor


1 Answers

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.

like image 195
Jared Smith Avatar answered Mar 26 '23 02:03

Jared Smith