JSFiddle - React, Tailwind, and code Playground

by Skooljester

HTML

<h2>Multiple show/hide in action</h2>

<h3>Section one: a div with a paragraph</h3>

<div class="toggle"><p>You can show/hide an entire div by giving it a class of "toggle". <a href="#">Links</a> and other child elements will work fine too. The element directly before this one is a heading, so it gets a show/hide link appended.</p></div>

<h4>Section two: single paragraph</h4>

<p class="toggle">A single paragraph can be hidden by giving it a class of toggle too. I can't help but be impressed by how easy it is to use jquery - even for someone with limited programming and javascript experience like me. Again, the preceding element is a heading.</p>

<p>Now: a list</p>

<ul class="toggle">

<li>You can even hide a list </li>

<li>Just give the &lt;ul&gt; the toggle class</li>

<li>This time the preceding element is a paragraph</li>

</ul>

JavaScript

$(document).ready(function() {
   // choose text for the show/hide link - can contain HTML (e.g. an image)
   var showText='Show';
   var hideText='Hide';

   // initialise the visibility check
   var is_visible = true;

   // append show/hide links to the element directly preceding the element with a class of "toggle"
   $('.toggle').prev().append(' (<a href="#" class="toggleLink">'+hideText+'</a>)');

   // hide all of the elements with a class of 'toggle'
   $('.toggle').show();

   // capture clicks on the toggle links
   $('a.toggleLink').click(function() {
      // switch visibility
      is_visible = !is_visible;
      // change the link depending on whether the element is shown or hidden
      $(this).html( (!is_visible) ? showText : hideText);
      // toggle the display - uncomment the next line for a basic "accordion" style
      //$('.toggle').hide();$('a.toggleLink').html(showText);
      $(this).parent().next('.toggle').toggle('slow');
      // return false so any link destination is not followed
      return false;
   });
});