Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It's not as straightforward as you might think. In jQuery, you detect clicks for individual elements of the DOM, so to determine if someone has clicked <em>outside</em> of a given area, you would have to bind a click event to the entire body and then deal with the separate clickable areas individually. </p> <p>(Binding a click to the entire body might not be the best idea speed-wise, so you may want to redesign the functionality of the tabs instead. Does the tab really need to collapse when the user clicks anywhere outside it? or will just clicking on the same heading to collapse the tab work? If so, go with @Dead Man's suggestion of a jQuery accordion.) Assuming that you really do need to implement tabs in the manner you describe, you could try something like the following:</p> <p>Using a modified version of your HTML:</p> <pre><code>&lt;div id="tabs" &gt; &lt;div class"expander"&gt;Click to expand Tab1&lt;/div&gt; &lt;div class="tab-text"&gt;Here is the text that appears when Tab1 is expanded&lt;/div&gt; &lt;div class"expander"&gt;Click to expand Tab2&lt;/div&gt; &lt;div class="tab-text"&gt;Here is the text that appears when the Tab2 is expanded&lt;/div&gt; &lt;/div&gt; </code></pre> <p>You would need some jQuery like this:</p> <pre><code>$( 'body' ).click( function( e ) { var $target = e.target; if( $target.is( '#tabs &gt; .expander' ) ) { // We show a given tab when the user clicks on the heading to reveal it. $target.next().show(); // You'll also need to decide what to do with the .expander itself. // (You could change its text using .text( 'Click to hide' ) or you // could just hide it until the user clicks outside all the tabs. } else if ( !( $target.is( '#tabs' ) || $target.is( '#tabs &gt; div' ) ) ) { // If the user clicks outside of all the tabs, we hide them. $( '#tabs &gt; .tab-text' ).hide(); } // Add all other click event handlers for the page here. if( $target.is( ...... ) ) { } }); </code></pre>
 

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