Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: if element is hidden, do action?

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.

like image 386
Jens Kvist Avatar asked Jun 18 '13 19:06

Jens Kvist


People also ask

How do I check if an element is hidden in jQuery?

To check if an element is hidden or not, jQuery :hidden selector can be used. .toggle() function is used to toggle the visibility of an element.

How do you know if an element is hidden?

Check if Element is Hidden with .is(":hidden") Alternatively, you can right-click on the page and select "Inspect" from the menu. In Firefox it's "Inspect element". .is(":hidden") will return true if the selected element is hidden. If it's not hidden, then it will return false .

How do you check if div is show or hide in jQuery?

Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.

How check textbox is visible or not in jQuery?

Syntax: $(element).is(":visible"); Example 1: This example uses :visible selector to check an element is visible or not using jQuery.


1 Answers

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

like image 81
supersize Avatar answered Sep 21 '22 00:09

supersize