Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery, detect if an element is already toggle

Tags:

jquery

toggle

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 !

like image 826
Clément Andraud Avatar asked Mar 12 '13 09:03

Clément Andraud


People also ask

How do you check if an HTML element is hidden in jQuery?

If you want to check visibility instead of display, you should use: . css("visibility") == "hidden" .

How check element is displayed or not 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 do you check if a button 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 can I tell if a div is in a viewport?

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.


3 Answers

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");
    }
});
like image 139
mattytommo Avatar answered Nov 02 '22 22:11

mattytommo


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"); 
like image 44
Adil Avatar answered Nov 02 '22 23:11

Adil


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/

like image 33
Waleed Asender Avatar answered Nov 03 '22 00:11

Waleed Asender