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.
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.
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 .
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.
Syntax: $(element).is(":visible"); Example 1: This example uses :visible selector to check an element is visible or not using jQuery.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With