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
<div data-id="red" class="option">Red</div>
<div data-id="yellow" class="option">Yellow</div>
<div data-id="blue" class="option">Green</div>
<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>
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>
<div class="option" data-color="yellow">Yellow</div>
<div class="option" data-color="green">Green</div>
<div id="red" class="colors"> This is content for red </div>
<div id="yellow" class="colors"> This is content for Yellow </div>
<div id="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:
<div class="option">Green</div>
...
<div id="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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="option" data-color="red">Red</div>
<div class="option" data-color="yellow">Yellow</div>
<div class="option" data-color="green">Green</div>
<div id="red" class="colors"> This is content for red </div>
<div id="yellow" class="colors"> This is content for Yellow </div>
<div id="green" class="colors"> This is content for Green </div>
Post a Comment for "Show Div Based On Selection & Hide Previous Div"