jscript

If This is Clicked Show This Else Hide This

AzDesign 2018. 2. 1. 09:59

Using data attributes is easy once you get the idea.

css

.redStuff, .blueStuff, .greenStuff {
  display: none;
 }

html

<ul id="color">
  <li id="red" data-color="red"><a href="#">Red</a></li>
  <li id="blue" data-color="blue"><a href="#">Blue</a></li>
  <li id="green" data-color="green"><a href="#">Green</a></li>
</ul>

<div class="redStuff" data-content="red">Red Stuff</div>
<div class="blueStuff" data-content="blue">Blue Stuff</div>
<div class="greenStuff" data-content="green">Green Stuff</div>

jquery

       // no need for the ids or classes
       // we set data attributes for the html
  $("li[data-color]").click(function(){
       // next line is for second click, to hide the prev div element
    $("div[data-content]").hide();
       // we are getting the data-color attr value here 
       // and for readibility  we assigned it to a variable called color
    var color = $(this).data("color");
       // find the div with the same content and show 
    $("div[data-content='"+color+"']").show();
  });

jsfiddle link to play with codes