Show Div Based On Selection & Hide Previous Div
I was wondering how it was possible to show a DIV by clicking on another DIV and then hiding a different DIV that was active before. I was messing around with the JQuery slideUp()
Solution 1:
Give a data-attribute to the divs and map with colors, the you can use like
<divdata-id="red"class="option">Red</div><divdata-id="yellow"class="option">Yellow</div><divdata-id="blue"class="option">Green</div><divid="red"class="colors"> This is content for red </div><divid="yellow"class="colors"> This is content for Yellow </div><divid="blue"class="colors"> This is content for Green </div>
jquery
$(".colors").hide();
$(".option").click(function(){
$(".colors").hide();
$("#"+$(this).data("id")).show();
});
Solution 2:
try
$(".colors").hide();
$('.option').click(function(){
$(".colors").hide();
$("#"+$(this).text().toLowerCase()).show();
});
Solution 3:
HTML: Red Yellow Green
<div id="red" class="colors"> This is content for red </div>
<div id="yellow" class="colors"> This is content for Yellow </div>
<div id="blue" class="colors"> This is content for Green </div>
JS:
$('.option').click(function(){
$('.colors').hide();
$('#' + $(this).data('id')).show();
});
Solution 4:
<div class="option" data-color="red">Red</div>
<divclass="option"data-color="yellow">Yellow</div><divclass="option"data-color="green">Green</div><divid="red"class="colors"> This is content for red </div><divid="yellow"class="colors"> This is content for Yellow </div><divid="green"class="colors"> This is content for Green </div>
$(".option").on("click",function(){
color = $(this).data("color");
$(".colors").slideUp();
$("#"+color).slideDown();
})
Solution 5:
You have a small mistake:
<divclass="option">Green</div>
...
<divid="blue"class="colors"> This is content for Green </div>
So using the name in the DIV to show the content may fail you.
Instead, you can include some unique identifying information in the divs you want to click. You can use jQuery's data() method.
$(".option").on("click", function(e){
var id = $(this).data("color");
$(".colors").hide(); // Hide all content DIVs
$("#"+id).show(); // Show the target DIV
})
.option{
display:inline-block;
border: solid 1px;
margin:5px;
padding:5px;
}
.colors {
display:none;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divclass="option"data-color="red">Red</div><divclass="option"data-color="yellow">Yellow</div><divclass="option"data-color="green">Green</div><divid="red"class="colors"> This is content for red </div><divid="yellow"class="colors"> This is content for Yellow </div><divid="green"class="colors"> This is content for Green </div>
Post a Comment for "Show Div Based On Selection & Hide Previous Div"