hide() / show() example

a simple jQuery example

by Mindy McAdams

HTML

<p>Below are four images -- click on them! </p>

<img id="theElephant" class="animalIcon" src="http://macloo.com/images/african_animals/elephant.png" alt="An animal icon">
<img id="theRhino" class="animalIcon" src="http://macloo.com/images/african_animals/rhino.png" alt="An animal icon">
<img id="theZebra" class="animalIcon" src="http://macloo.com/images/african_animals/zebra.png" alt="An animal icon">
<img id="theLion" class="animalIcon" src="http://macloo.com/images/african_animals/lion.png" alt="An animal icon">

<!-- below are four divs, but all are hidden b/c of jQuery -->


<div id="rhinoStuff">
  <p>Here is rhino stuff.</p>
</div>
<div id="elephantStuff">
  <p>Here is elephant stuff.</p>
</div>
<div id="zebraStuff">
  <p>Here is zebra stuff.</p>
</div>
<div id="lionStuff">
  <p>Here is lion stuff.</p>
</div>

CSS

body {
  font-family: Calibri, sans-serif;
}

div {
  text-align: center;
  padding: 10px 0;
}

#elephantStuff {
  background: #239d9a;
}

#lionStuff {
  background: #ffbaa3;
}

#rhinoStuff {
  background: #ffe9ad;
}

#zebraStuff {
  background: #ca6996;
}

JavaScript

// jQuery hide()/show() example with a switch statement 

$(document).ready(function() {


  // function to hide all divs 
  function hideAll() {
    $('#elephantStuff').hide();
    $('#rhinoStuff').hide();
    $('#zebraStuff').hide();
    $('#lionStuff').hide();
  }

  // run that function right away
  hideAll();

  // when any animal is clicked, make the suitable div appear
  $('.animalIcon').click(function() {
  
    // but first, hide all the divs to ensure that 
    // only one will be open, ever 
    hideAll();

    // here is a switch statement - this was in Codecademy 
    // "Control Flow" lesson 7

    // we can get the ID of the thing that was clicked - 
    switch ($(this).attr("id")) {
      case "theElephant":
        $('#elephantStuff').show();
        break;
      case "theRhino":
        $('#rhinoStuff').show();
        break;
      case "theZebra":
        $('#zebraStuff').show();
        break;
      case "theLion":
        $('#lionStuff').show();
        break;
    }
  }); // end of function for clicking 


});