How to show and hide div one by one using jquery?

Here, Suppose, have 3 Div, like Div-1,Div-2,Div-3. Now when I clicked the button , then Div-1 will hide. then Div-2, then Div-3. Finally All Div is hidden. Then when clicked again Div-1 will show, then Div-2 will show, Then Div-3 will show. This type it will function every time on clicking the button.

Here, Full page code is Given below,

<!DOCTYPE html>
<html>
<head>
<title>Demo - Show and Hide Div</title>
<meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
	<div class="row main_block">
		<div class="col-sm-4 sub_block sub_block_1">
			<h3>Column 1</h3>
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
			<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
		</div>
		<div class="col-sm-4 sub_block sub_block_2">
			<h3>Column 2</h3>
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
			<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
		</div>
		<div class="col-sm-4 sub_block sub_block_3">
			<h3>Column 3</h3>        
			<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
			<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris...</p>
		</div>
	</div>
	<div class="row">
		<div class="col-sm-12">
			<button class="btn btn-primary clickme">Click Me!</button>
		</div>
	</div>
</div>

<script type="text/javascript">
	$(function(){
		var sub_blocks = [];
		$("div.main_block").find('div.sub_block').each(function(key,val){
			let subdiv_cls = 'sub_block_'+(key+1);
			sub_blocks.push(subdiv_cls);
		});	
		var blocks_display 	= sub_blocks;
		var blocks_hide 	= [];
		var pointdisplay = true; 
		$('button.clickme').on('click', function(){
			if(pointdisplay){
				var cls = blocks_display.shift();
				blocks_hide.push(cls);
				if(blocks_display.length == 0){ pointdisplay = false; }
			}else{
				var cls = blocks_hide.shift();
				blocks_display.push(cls);
				if(blocks_hide.length == 0){  pointdisplay = true; }
			}

			$('div.sub_block').show();
			$.each(blocks_hide, function(key,divclass){
				$('.'+ divclass).hide();
			})
		});
			
	});
</script>
</body>
</html>

Check Demo : https://jsfiddle.net/devchandansh/c3qu924h/

Leave a Comment