Show/ hide a div element at a time with jQuery

Here I would like to give a tutorial that if you have few div elements which you like to show/hide at a time with jQuery while clicking on a button. Its need a simple line of code for running through jQuery. First just call the jquery file from jquery website or download your server and call from it self.
show-hide-div-with-jquery

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>

HTML part

<div class="btnCntnr">
	<input class="btns" type="button" value="cbox1" id="b1" />
	<input class="btns" type="button" value="cbox2" id="b2" />
	<input class="btns" type="button" value="cbox3" id="b3" />
</div>
<div>
	<div id="cbox1" style="display:block;"></div>
	<div id="cbox2" style="display:none;"></div>
	<div id="cbox3" style="display:none;"></div>
</div>

Here what we are going to do is, getting the value and assign to a variable. That value should be match with div ids. While clicking on each buttons it will set the set the css style property display to block and other div elements to display none. See the jQuery code below.

jQuery Part

<script>
	$(document).ready(function(){
		$('.btns').click(function(){
		var btnv = this.value;
			$('#'+btnv).show('slideUp').siblings().hide('slideDown');
		})
	})
</script>

This css part is for just styling my demo only. So you should create your own styles.

<style>
	.btns{
		width:36px;
		height:32px;
		text-indent:-2000px;
		border:none;
	}
	.btnCntnr{padding-left:28px;}
	.btns#b1{
	background:url(images/buttons_bg.jpg) no-repeat 0 0;
	}
	.btns#b2{
	background:url(images/buttons_bg.jpg) no-repeat -46px 0;
	}
	.btns#b3{
	background:url(images/buttons_bg.jpg) no-repeat -92px 0;
	}
	#cbox1, #cbox2, #cbox3 {width:364px; height:140px;}
	#cbox1{
		background:url(images/div_bgs.jpg) no-repeat;
	}
	#cbox2{
		background:url(images/div_bgs.jpg) no-repeat 0 -142px;
	}
	#cbox3{
		background:url(images/div_bgs.jpg) no-repeat 0 -283px;
	}
</style>
[Download not found]
Share with Friends
[Facebook] [Jamespot] [Reddit] [StumbleUpon] [Twitter] [Email]

Leave a Reply

Your email address will not be published. Required fields are marked *