Tabs Using Javascript / Jquery

Posted on Posted in Javascript, Technology

Hello Folks, this is very first post by webtechbuddies in Javascript. Most of the time we need tabs, Instead of including full plugin file we can use this tabs logic. Because it will lighten your project to use the only code you need to run your functionality. Let’s start, first of all we need to include jQuery in our HTML file, you can check with latest version of jQuery from Here. Then we need to include them on top of page intag.

<!DOCTYPE html>
<html lang="en">
	<head>
		<title>Tabs</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">		
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
	</head>
	<body>
		<div class="container">
			<h2>Tabs</h2>
			<ul class="nav nav-tabs">
				<li class="active"><a href="#tab1">Tab 1</a></li>
				<li><a href="#tab2">Tab 2</a></li>
				<li><a href="#tab3">Tab 3</a></li>
			</ul>

			<div class="tab-content">
				<div id="tab1" class="tab-pane fade in active">
					<h3>Tab1</h3>
					<p>Show content of first tab.</p>
				</div>
				<div id="tab2" class="tab-pane fade">
					<h3>Tab2</h3>
					<p>Show content of second tab.</p>
				</div>
				<div id="tab3" class="tab-pane fade">
					<h3>Tab 3</h3>
					<p>Last but not the least tab.</p>
				</div>
			</div>
		</div>
	</body>
</html>

Here I used one more library i.e CSS file to look the design good (not compulsory at your end). If need add this line just above the jQuery script tag in file.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

jQuer Last but not the least the script logic, put this logic at the end of file and the run.

<script type="text/javascript">
$(document).ready(function(){
	$('.nav li a').click(function()
	{
		var currentLI = $(this).attr('href');
		$(this).parent().siblings().removeClass('active');//remove active class from all li menus
		$(this).parent().addClass('active'); //add the active clas to current menu		
		$('.tab-pane').removeClass('in active'); //hide all the tabs 
		$(currentLI).addClass('in active'); //open the current one
	});
});
</script>

Or, you can simply download this file and directly put on your system , run it. If still you are facing any issue while integrating Tabs, you are free to ask or contact me.