javascript - If This is Clicked Show This Else Hide This -
i have seen other if else examples on here nothing addressing jquery "if clicked show else hide this". here's simple code example. know cleanest way show .redstuff when #red clicked else hide , show other classes when relative id clicked. here html:
.redstuff, .bluestuff, .greenstuff { display: none; }
<ul id="color"> <li id="red"><a href="#">red</a></li> <li id="blue"><a href="#">blue</a></li> <li id="green"><a href="#">green</a></li> </ul> <div class="redstuff">red stuff</div> <div class="bluestuff">blue stuff</div> <div class="greenstuff">green stuff</div>
using data attributes easy once 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 ids or classes // set data attributes html $("li[data-color]").click(function(){ // next line second click, hide prev div element $("div[data-content]").hide(); // getting data-color attr value here // , readibility assigned variable called color var color = $(this).data("color"); // find div same content , show $("div[data-content='"+color+"']").show(); });
Comments
Post a Comment