Jquery: if element is hidden, do action?

Jens Kvist picture Jens Kvist · Jun 18, 2013 · Viewed 21.8k times · Source

Hello I searched a bit on the internet, but didn't find what I actualy were looking for. But anyway, what I'm looking for is some like if a element is hidden then it's gonna do an action, and then if the element is visible it's gonna do another action. In this case I'm building an show/hide menu, when you click the menu icon (with the class ".toggle") it's gonna change the opacity to 1, and when you hide the menu the icon opacity will change to 0.6 again.

Here's my code anyway:

$(".sidebar_menu").hide();
$(".sidebar li.toggle").click(function(){
$(".sidebar_menu").animate({width: "toggle"}, 200);
// Here's where the code I can't figure out is gonna be.
});

Hope you guys wanna help me, it would be nice! Thank you.

Answer

supersize picture supersize · Jun 18, 2013

this works for hidden and visible elements:

$(".sidebar_menu").hide();
$(".sidebar li.toggle").click(function(){
  $(".sidebar_menu").animate({width: "toggle"}, 200,
    function() {
      if($(this).is(':visible')){
        $(".toggle").css({opacity: 1});
      } else if ($(this).is(':hidden')) {
        $(".toggle").css({opacity: 0.6}); 
      }; 
    })
  });
}); 

Edit: with .toggle()

$(".sidebar_menu").hide();
$(".sidebar li.toggle").click(function(){
  $(".sidebar_menu").toggle('slow',
    function() {
      if($(this).is(':visible')){
        $(".toggle").css({opacity: 1});
      } else if ($(this).is(':hidden')) {
        $(".toggle").css({opacity: 0.6}); 
      }; 
    })
  });
});

Here you see a small example: FIDDLE