Top toggle Questions

List of Tags
Philip Morton

In jQuery, suppose you have an element of some kind that you're hiding and showing, using .hide(), .show() or .toggle(). How do you test to see if that element is currently hidden or visible on the screen?

Answered By: Tsvetomir Tsonev ( 2263)

As, the question refers to a single element, this code might be more suitable:

$(element).is(":visible") // Checks for display:[none|block], ignores visible:[true|false]

Same as twernt's suggestion, but applied to a single element.

I want to toggle a variable between 0 and 1. If it's 0 I want to set it to 1, else if it's 1 I want to set it to 0.

This is such a fundamental operation that I write so often I'd like to investigate the shortest, clearest possible way of doing it. Here's my best so far:

v = (v == 0 ? 1 : 0);

Can you improve on this?

Edit: the question is asking how to write the above statement in the fewest characters while retaining clarity - how is this 'not a real question'? This wasn't intended to be a code-golf exercise, though some interesting answers have come out of people approaching it as golf - it's nice to see golf being used in a constructive and thought-provoking manner.

Answered By: Guffa ( 492)

You can simply use:

v = 1 - v;

This of course assumes that the variable is initialised properly, i.e. that it only has the value 0 or 1.

Another method that is shorter but uses a less common operator:

v ^= 1;


To be clear; I never approached this question as code golf, just to find a short way of doing the task without using any obscuring tricks like side effects of operators.