Jquery: if element is hidden, do action?
Asked Answered
D

1

7

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.

Dah answered 18/6, 2013 at 19:1 Comment(1)
Sorry could you elaborate on the problem? Possibly showing an example on www.jsfiddle.net ?Caliber
P
9

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

Peevish answered 18/6, 2013 at 19:5 Comment(2)
There seems like there's Transformers with this one (more than meets the eye) Im sure saying .is(':visible') would work but I am willing to bet there's more to this.Caliber
I have one more question @supersize... How do I do the same thing but with .toggle instead of the animation? :-)Dah

© 2022 - 2024 — McMap. All rights reserved.