jQuery live function and add/remove class

3.1k Views Asked by At

I'm using jquery 1.5 and I'm having an issue with the add and remove class function . Below is my code.

I'm creating a navigation with a normal, hover, and active state. The active state I want to add and remove the class.

  $(".class").hover(function(){
          $(this).css("background-color", "#666).css("color", "yellow");
    ), function(){ 
         $(this).css("background-img", url(image).css("color","#fff");
    ).live('click', function(){
           if($("ul.me li").hasClass("current")){
             $("ul.me li").removeClass("current");
                $(this).addClass("current");
             }
        });


<ul class="me">
   <li class="current"> item1 </li>
   <li> item1 </li>
   <li> item1 </li>
</ul>

Did I bind this on correctly?

4

There are 4 best solutions below

0
Adil On

You probably need to use $("ul.me li").removeClass("current") instead of $("ul#me li").removeClass("current")

$("selector").live('click', function(){
   if($("ul.me li").hasClass("current")){
     $("ul.me li").removeClass("current");
        $(this).addClass("current");
     }
});
1
Harshit Tailor On

you missing selector :-

$("ul.me li").live('click', function(){
   if($("ul.me li").hasClass("current")){
     $("ul#me li").removeClass("current");
        $(this).addClass("current");
     }
});
0
tank On

Just .live doesn't make sense. You need to set .live to jquery object like $('selector')

0
Jehanzeb.Malik On

You are over complicating things in your script. You need to read the documentation for .css. You can not refer to an element by $(".class"). If you want to refer to an element type use only the name without the . or # like $("ul"). If you want to refer to a class use $(".me") and $("#idName") for ids. Single css command can take an array of css values to change. As I said earlier please go through css documentation. jQuery 1.6 was as close as I was able to get in jsfiddle. Here is a fiddle link. Please refer to the script and modify css values to your requirement.

Fiddle

Note: If you are adding a class to li and removing on hover, add styles to the class in css rather than in js. It is cheaper.