Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As has been mentioned, jQuery can make this very straightforward, but your major code saving is going to come from taking advantage of event bubbling. You can do this is you structure your HTML something like this:</p> <pre><code>&lt;div id="topics"&gt; &lt;div class="item"&gt; &lt;div class="show"&gt; show text 1 &lt;/div&gt; &lt;div class="hide"&gt; hide text 1 &lt;/div&gt; &lt;div class="text"&gt; this is the text to be shown 1 &lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div class="show"&gt; show text 2 &lt;/div&gt; &lt;div class="hide"&gt; hide text 2 &lt;/div&gt; &lt;div class="text"&gt; this is the text to be shown 2 &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Now instead of attaching an <code>onclick</code> handler to each end every <code>div</code>, attach it to the parent element. To do this with jQuery:</p> <pre><code>$(window).load(function(){ //Do this when the page loads $('#topics').bind('click', function(event) { //Find the element with ID 'topics' and attach a click handler var t = $(event.target); //event.target is the element that was actually clicked, $() gets the jQuery version of it if(t.hasClass('show')) { //If it is a 'show' element... t.siblings('.hide').show(); //...show the other two elements... t.siblings('.text').show(); t.hide(); //...and hide the clicked element } if(t.hasClass('hide')) { //If it is a 'hide' element... t.siblings('.show').show(); //...show the 'show' element... t.siblings('.text').hide(); //...and hide the other two t.hide(); } }); }); </code></pre> <p>And that's it! <a href="http://jsfiddle.net/robertc/JJTnT/" rel="nofollow">Here's a demo</a>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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