Bilisim

tabs

Create a Simple HTML5 Tabs Using jQuery

Content tab is a great way for space utilization and to cataloging. They are easy to implement and almost every UI library has one or other flavor of tabs.

Today I’ll show you step by step process to create simple and effective jQuery Plugin for HTML5 based Content Tab.

Jump into your favorite web editor (like Sublime Text, Notepad++, Vim etc) and create a file called index.html with the following content to start with.

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset=utf-8 />
<title>HTML5 jQuery Tabs</title>
</head>
<body>
  <div class="tabs">
    <a data-toggle="tab1">Tab1</a>
    <a data-toggle="tab2">Tab2</a>
    <a data-toggle="tab3">Tab3</a>
    <a data-toggle="tab4">Tab4</a>
    <a data-toggle="tab5">Tab5</a>
  </div>
<div class="tabContent">  
  <div id="tab1">
    <h5>Tab1</h5>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eget sollicitudin nibh. Duis semper, diam sed iaculis dictum, libero erat molestie dui, ac suscipit felis leo sed ipsum. </p>
  </div>
  
  <div id="tab2">
    
    <h5>Tab2</h5>
    <p>Donec pellentesque sapien neque, ac lobortis erat facilisis quis. Praesent faucibus arcu eros. Proin id tortor euismod, vulputate neque id, placerat nunc.</p>
  </div>
  
  <div id="tab3">
    <h5>Tab3</h5>
    <p>Duis justo mi, egestas euismod placerat a, eleifend vitae lacus. Integer non odio nec libero lacinia vulputate. Phasellus ante lectus, congue vel volutpat vitae, dictum quis est. </p>
  </div>
  
  <div id="tab4">
    <h5>Tab4</h5>
    <p>Nulla varius sit amet augue vel consequat. Aenean faucibus vehicula interdum. Integer eleifend, lectus eget vulputate feugiat, nibh nulla congue ipsum, eu mattis tortor nulla vitae diam. Maecenas rutrum risus non libero ullamcorper, nec vehicula sapien tincidunt. </p>
  </div>
  
  <div id="tab5">
    <h5>Tab5</h5>
    <p>Suspendisse vulputate ornare dui, sed luctus est mattis nec. Curabitur ut dolor eleifend, vulputate purus et, ullamcorper tortor. In posuere ultricies lectus. Vestibulum vitae odio ut est sagittis porta. </p>
  </div>
  
</div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="html5jtabs.js"></script>
<script>
$(function() {
  $(".tabs a").html5jTabs();
});
</script>
</body>
</html>

From the above HTML, you can see that I’ve created five different DIV with some dummy content with id tab1 to tab5. Also, there are five anchor tags denoting each of the tab content.

I’ve included two external js file just before closing BODY tag. One is latest jquery library and second is the jQuery plugin you are going to create in this tutorial.

Time for some look and feel for the tabs.

You can style the way you like, refer different UI formats for tabs or use your own creativity. Here, I’ll use simple styling for the sake of understanding the functionality.

Create a file called style.css and paste the following code. This stylesheet is already included in the above HTML using LINK tag.

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.tabs a{
  cursor: pointer;
  padding: 5px;
  background: #fff;
  color: #000;
  border: 1px solid #666;
  border-bottom: 0;
}
.tabs a:hover, .tabs a.active{
  background: #666;
  color: #fff;
}

.tabContent{
  border: 1px solid #aaa;
  margin: 4px 0;
  padding: 5px;
}

Fire your favorite browser and open index.html to view something similar to the following.

HTML5 jQuery Tabs

If you are getting the same result then you are good to go, if not check your stylesheet’s and script’s file path. All of them should be placed in the same folder.

Now, we’ll create a jQuery plugin to get some action. Let’s just jump and write some code first. I’ll explain it in just a moment.

Javascript

1
2
3
4
5
;(function($){
  $.fn.html5jTabs = function(options){
     // Add your plugin code here.
  };
}(jQuery));

The code mentioned above is the simplest jQuery plugin’s pattern. For more information on different Plugin Patterns refer the post Essential jQuery Plugin Patterns

Now we’ll add some functionality to our plugin.

Javascript

1
2
3
4
5
6
7
;(function($){
  $.fn.html5jTabs = function(options){
    return this.each(function(index, value){
       
    });
  };
}(jQuery));

return this.each() will apply the whatever code you have written inside the plugin to all the selected items with jQuery selector. For example if there are five elements with same class called “slider” and if you apply your custom plugin “cutomSlider” to the selector of that class : $(".slider").cutomSlider(); than “each()” function will find all the elements with the selected class and apply jQuery method called customSlider() to all of them.

The “return” keyword is used for retaining the “Statement Chaining”.

Full plugin Code

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
;(function($){
  $.fn.html5jTabs = function(options){
    return this.each(function(index, value){
      var obj = $(this),
      objFirst = obj.eq(index),
      objNotFirst = obj.not(objFirst);
      
      $("#" +  objNotFirst.attr("data-toggle")).hide();
      $(this).eq(index).addClass("active");
      
      obj.click(function(evt){
        
        toggler = "#" + obj.attr("data-toggle");
        togglerRest = $(toggler).parent().find("div");
        
        togglerRest.hide().removeClass("active");
        $(toggler).show().addClass("active");

        //toggle Active Class on tab buttons
        $(this).parent("div").find("a").removeClass("active");
        $(this).addClass("active");

        return false; //Stop event Bubbling and PreventDefault
      });
    });
  };
}(jQuery));

Code Explanation

Step1: Defining some variables

1
2
3
var obj = $(this),
      objFirst = obj.eq(index),
      objNotFirst = obj.not(objFirst);

$(this) is a jQuery object compared to “this”, which refers to a DOM element. When we are inside the “each()” function $(this) refers to the current index of element’s array which was created by each function. Know more on jQuery $(this).

The variable “obj” is $(this), objFirst refers to the first element in the array of elements and objNotFirst refers to all elements except the first element. This convenience has been used for code re-usability.

Step2: Hide all the elements except the first element when plugin initializes using jQuery “hide()” method.

1
$("#" +  objNotFirst.attr("data-toggle")).hide();

Step3: Add the “active” class to first tab

1
$(this).eq(index).addClass("active");

Step4: Respond to the click event and toggle the tab content.

1
2
3
4
5
6
7
8
9
10
11
12
13
obj.click(function(evt){ 
    toggler = "#" + obj.attr("data-toggle");
    togglerRest = $(toggler).parent().find("div");

    togglerRest.hide().removeClass("active");
    $(toggler).show().addClass("active");

        //toggle Active Class on tab buttons
        $(this).parent("div").find("a").removeClass("active"); 
        $(this).addClass("active");

    return false; 
});

The two variables “toggler” and “togglerRest” selects the current tab content and all them respectively. When on tab is clicked it will select the element with the ID which is equal to it’s own “data-togle” attribute and displays it using jQuery “show” method and hides rest of them, the later should come first while coding. The “data-XXX” is HTML5 attribute.

return false will stop the event bubbling and default click even of the anchor tag.

Now call the plugin when document loads.

1
2
3
$(document).ready(function() {
  $(".tabs a").html5jTabs();
});

Demo

Bugün 35 ziyaretçi burdaydı!

Genel

Uni Kisayollar

Onemli Linkler

Bilisim

CSS,HTML,XML...

Linkler

Flatcast Radyo

Active-x

Bu web sitesi ücretsiz olarak Bedava-Sitem.com ile oluşturulmuştur. Siz de kendi web sitenizi kurmak ister misiniz?
Ücretsiz kaydol