Hide div on div click and show second div
This is my html code ... In this I have set div-display: none, just want that when I click on the first div which is gray ... the second div appears and disappears from the first and third div and when I click on second div, third and first div disappear .... please help me. I'm new to the website ...
<div class="row">
<div class="col-md-6">
<div style="background:grey">
text here
</div>
<div style="background:blue;display:none">
text here
</div>
<div style="background:green;display:none">
text here
</div>
</div>
</div>
source to share
When clicking on the outer .col-md-6
div, you can find the currently visible one div
using a selector :visible
. Then you can hide()
, and show()
next()
. Try the following:
$('.col-md-6').click(function() {
$(this).find('div:visible').hide().next().show();
});
Alternatively, if you don't want anyone hiding the final div
:
$('.col-md-6').click(function() {
var $current = $(this).find('div:visible');
var $next = $current.next()
if ($next.length) {
$current.hide();
$next.show();
}
});
Or finally, if you want to loop through all divs, back to the beginning as soon as you reach the end:
$('.col-md-6').click(function() {
var index = $(this).data('index') || 1;
var $divs = $(this).find('div');
$divs.hide().eq(index % $divs.length).show();
$(this).data('index', ++index);
});
source to share
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){
$("#blue").hide();
$("#green").hide();
$("#grey").on("click",function(){
$("#blue").show(3000);
$("#grey").hide(2000);
$("#green").hide(2000);
});
$("#blue").on("click",function(){
$("#green").show(3000);
$("#blue").hide(2000);
$("#grey").hide(2000);
});
$("#green").on("click",function(){
$("#grey").show(3000);
$("#blue").hide(2000);
$("#green").hide(2000);
});
});
</script>
<div class="row">
<div class="col-md-6">
<div style="background:grey;height:50px" id="grey">
text here
</div>
<div style="background:blue;height:50px" id="blue">
text here
</div>
<div style="background:green;height:50px" id="green">
text here
</div>
</div>
</div>
</body>
</html>
source to share