Tuesday 2 September 2014

How to make simple Javascript tab with css and html?

In this session we will write a tabs structure with the help of jquery, html & css.

When you are writing some content on your webpage, then it is better practice that showing your content in a tab format than normal text format. This let your page looks more cleaner than normally formatted text.

If you find tabs jquery on google you will get jquery plugins that will force you to keep unnecessarily heavy js and css files on your webpage, which let slowdown your page. In this session we will write a tabs structure with the help of jquery, html & css.




First of all we will write simple html given below. We are using 'ul', 'li' as tabs(tab heading) and below that we will use 'div' for contain your html code. Each div is having id. You can change internal html as per your requirement. Tabs 'li' is having rel properties containing value of  id of targeted div that to be shown.

/************************Html**********************/

<div class="tabcontainer">

<ul class="tabheading">

                    <li class="active" rel="tab1"><a href="javascript:return false;">Tab 1</a> </li>

                    <li rel="tab2"><a href="javascript:return false;">Tab 2</a> </li>
</ul>



<div class="tabbody active" id="tab1" style="display: block;">
Tab 1
Your Text or html

</div>

<div class="tabbody" id="tab2" style="display: none;">
Tab 2
Your Text or html

</div>

</div>


Below is css for our tab. You may do styling of your tab as you want.


/************************Css************************/
.tabcontainer {
float: left;
width: 100%;
}
.tabheading li.active {
background-color: #fff;
border-bottom: 0;
margin-bottom: -1px;
}
.tabheading li {
display: inline-block;
border: 1px solid #ddd;
background-color: #eee;
margin: 0;
}
.tabheading li a { 
padding: 0 2%; 
}
.tabbody.active {
display: block;
}
.tabbody {
border: 1px solid #ddd;
float: left;
min-height: 10px;
width: 96%;
padding: 2%;
display: none;
}


Now main part of our structer that is our Javascript. Copy & paste this small code given below on your webpage at bottom.

/*****************************Js************************/
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script>
 $('.tabheading li').click(function () {
        var tabid = $(this).attr("rel");
        $(this).parents('.tabcontainer').find('.active').removeClass('active');
        $('.tabbody').hide();
        $('#' + tabid).show();
        $(this).addClass('active');

        return false;
    });
</script>


In this script on click of tab heading li we are reading id from 'rel' property of it and showing div with that id

1 comment: