Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Toggle - any way to know which (hide or show) is being applied?

Tags:

jquery

I'm working in Adobe AIR, and I have a list of divs that show expanded information for each list item in a hidden div on a click - like so:

$(this).click(function(){
 $(this).next('div.info').toggle();
});

This extends the height of the whole app, so eventually, if the user were to expand all of the divs, there'd be a scrollbar on the side. To get around this, I want to adjust the height of the window (either growing or shrinking, depending). I have all of the code working, except I can't figure out how to get inside the .toggle function to find out which effect (hide or show) is going to be applied. Setting my if() statement to key on the end-state of the info div doesn't work, because it assesses the div immediately on the click.

Is there any way to know which .toggle is being applied in jQuery so I can use that state change to apply my other changes?

like image 950
b. e. hollenbeck Avatar asked Mar 28 '09 21:03

b. e. hollenbeck


People also ask

How do you toggle between hiding and show an element in jQuery?

jQuery toggle() MethodThe toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.

How do I know if a div is hide or show?

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 does toggle work in jQuery?

The toggle() method attaches two or more functions to toggle between for the click event for the selected elements. When clicking on an element, the first specified function fires, when clicking again, the second function fires, and so on. Note: There is also a jQuery Effects method called toggle().

How do I toggle between buttons in JavaScript?

A tgl() method is utilized to toggle a button in JavaScript. In this method, you extract the HTML element by employing the getElementById property, and then the if else-if statement is added to it. If the “value==ON”, toggle the value to “OFF”. If the value is OFF, then the value will be toggled to “ON”.


2 Answers

After the toggle finishes, you can know which div was toggled:

var visible = $(this).next('div.info').toggle().is(":visible");
if(visible){
  alert("Hey! I've just showed up here!");
}

That way you'll know if the recent toggle operation showed the div or not.

like image 101
Seb Avatar answered Oct 08 '22 00:10

Seb


You can test this with:

if ($(selector).is(':visible')) {
   // do something
}
like image 21
Matt Good Avatar answered Oct 07 '22 23:10

Matt Good