I need with jQuery to know if an element on my page is already toggle or not.
I have a menu with XXX elements.
When i click on an element, i use : $("#elementXX").slideToggle("slow");
(XX is a number)
If i click on another element, i need to know if an element is already toggle, and i need to close this element before to slideToggle my new element.
How can i do that ? I can't check id by id like #element1, #element2, #element3 etc....
Thanks !
If you want to check visibility instead of display, you should use: . css("visibility") == "hidden" .
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.
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.
If the <div> element is in the viewport, its top and left are always greater than or equal zero. In addition, its distance from the right is less than or equal to the width of the viewport, and ids distance from the bottom is less than or equal to the height of the viewport.
You don't need toggle, slideUp
and slideDown
are a much better fit for your scenario. You can simply do:
$("#clickedItem").click(function () {
var wasVisible = $("#elementXX").is(":visible");
$("[id^=element]:visible").stop().slideUp("slow");
if (!wasVisible) {
$("#elementXX").slideDown("slow");
}
});
You can set the data attributes to some value to know if it is toggled. You can add the attributes in html or use script straightaway to add.
$("#elementXX").data("toggled", "true");
According to jQuery official website FAQ:
$("#toggleButton").click(function () {
if ($("#elementXX").is(":visible")) {
// toggled down
}
if ($("#elementXX").is(":hidden")) {
// toggled up
}
});
https://learn.jquery.com/using-jquery-core/faq/how-do-i-determine-the-state-of-a-toggled-element/
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