Show and Hide product li using jquery

I have a list

<ul class="products">
   <li class="products">first</li>
   <li class="products">second</li>
   <li class="products">third</li>
   <li class="products">fourth</li>
</ul>

and I want to use jquery to: 1-hide other li s when user clicks on one except the clicked one. 2-show all li s when user clicks again on the active li.

this is the script:

$(window).load(function(){
$(".products li.active").click(function(){
    $(".products li").show("slow");
    $(this).removeClass("active");
});
$(".products li").click(function(){
    $(this).addClass("active");
    $(".products li:not(.active)").hide("slow");
});
});  

it works for the first step, but when user clicks on active li nothing changes.

Answers


Try this:

$(window).load(function(){
   $(".products li").click(function(){
      if ($(this).hasClass("active")) {
          //this is already active, show all
          $(".products li").show("slow");
          $(this).removeClass("active");
      } else {
          //this is not active yet, make active and hide all others
          $(this).addClass("active");
          $(".products li:not(.active)").hide("slow");
      }
   });
}); 

Live demo available here on JsFiddle


Need Your Help

Center fixed text during canvas scroll in Android

android canvas scroll watermark drawtext

I am trying to create a watermark text to my custom view, but the problem is when I scroll the canvas, I am unable to determine the exact co-ordinates of the screen's center.

Update Image source from AJAX success function

javascript jquery ajax

I use to update Label values inside the AJAX success function like below, But I need to know how I'm going to apply this method to change/update "src" of an &lt;img id="myimage" src=""/&gt;

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.