Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Easy peasy.</p> <pre><code>$(function () { var $main = $('#main'), $1 = $('#1'), $2 = $('#2'); $2.hide(); // hide div#2 when the page is loaded $main.click(function () { $1.toggle(); $2.toggle(); }); }); </code></pre> <p><a href="http://jsfiddle.net/mattball/8vbGE/" rel="nofollow noreferrer">jsfiddle demo &#x2192;</a></p> <hr> <h3>Edit</h3> <p>OP Comment: <em>"Is there anyway i can keep track of which div is visible?"</em></p> <p>There certainly is; it depends on how you want to use it. You can manually maintain a flag:</p> <pre><code>$(function () { var $main = $('#main'), $1 = $('#1'), $2 = $('#2'), $visible; $2.hide(); // hide div#2 when the page is loaded $visible = $1; $main.click(function () { $1.toggle(); $2.toggle(); $visible = ($visible === $1 ? $2 : $1); }); }); </code></pre> <p>Or you can just write a function that figures it out for you:</p> <pre><code>$(function () { var $main = $('#main'), $1 = $('#1'), $2 = $('#2'); $2.hide(); // hide div#2 when the page is loaded $main.click(function () { $1.toggle(); $2.toggle(); }); function whichIsVisible() { if (!$1.is(':hidden')) return $1; if (!$2.is(':hidden')) return $2; } }); </code></pre> <p>As <a href="https://stackoverflow.com/users/305000/jandy">jAndy</a> points out, this function can be written in a more concise/terse form:</p> <pre><code>function whichIsVisible() { return $1.add($2).filter(':visible'); } </code></pre> <p>However, it <strong>is semantically different</strong> from the first version. The first version returns one of:</p> <ul> <li><code>$1</code></li> <li><code>$2</code></li> <li><code>undefined</code></li> </ul> <p>while jAndy's version returns one of:</p> <ul> <li><code>$1</code></li> <li><code>$2</code></li> <li><code>$1.add($2)</code>, a two-element jQuery object</li> <li><code>$()</code>, an empty jQuery object</li> </ul> <p>So they're <strong>not strictly equivalent</strong>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload