My first jQuery plugin "tabul8"
posted: 25 Jan 2012
So I needed to do a simple tabbed menu. Check this out.
1 // javascript
2
3 // jQuery required
4
5 ( function ( $ ){
6 $ . fn . extend ({
7
8 tabul8 : function () {
9 var args = arguments [ 0 ];
10 var binded = $ ( this ). children (). bind ( 'click' , function ( e ) {
11 var elem = $ ( e . target );
12 var attr = elem . attr ( 'data-callback' );
13 if ( elem [ 0 ]. tagName == 'A' ) e . preventDefault ();
14 if ( attr !== undefined && attr !== false && ! elem . hasClass ( 'selected' ))
15 eval ( attr + '();' );
16 if ( ! elem . hasClass ( 'selected' )) {
17 elem . parent (). find ( '.selected' ). removeClass ( 'selected' );
18 elem . addClass ( 'selected' );
19 }
20 });
21
22 if ( typeof args != 'undefined' ) {
23 for ( key in args ) {
24 switch ( key ) {
25 case 'selected' :
26 $ ( this ). children ( ':eq(' + args [ key ] + ')' ). click ();
27 break ;
28 }
29 }
30 }
31 return binded ;
32 }
33
34 });
35 })( jQuery );
36
37 // Callbacks
38 var bing = function () {
39 alert ( 'BING' );
40 };
41
42 var bang = function () {
43 alert ( 'BANG' );
44 };
45
46 $ ( document ). ready ( function () {
47 $ ( '#tabs' ). tabul8 ({ selected : 0 });
48 });
1 /* css */
2
3 body {
4 padding-top : 10 px ;
5 padding-left : 5 px ;
6 }
7
8 # tabs {
9 margin : 0 ;
10 padding : 0 ;
11 font-family : Arial ;
12 font-size : 1.3 em ;
13 float : left ;
14 width : 100 % ;
15 position : absolute ;
16 }
17
18 # tabs a {
19 display : block ;
20 float : left ;
21 padding : 10 px ;
22 margin-right : 10 px ;
23 text-align : center ;
24 border : 1 px solid #666 ;
25 background-color : #666 ;
26 text-decoration : none ;
27 color : #FFF ;
28 line-height : 1.3 em ;
29 cursor : pointer ;
30 }
31
32 # tabs a . selected {
33 border-bottom : 1 px solid #FFF ;
34 background-color : #FFF ;
35 color : #666 ;
36 }
37
38 . divide {
39 width : 100 % ;
40 height : 48 px ;
41 border-bottom : 1 px solid #666 ;
42 }
43
44 . clearer {
45 clear : both ;
46 }
1 <!-- html -->
2
3 < div id = "tabs" >
4 < a href = "#" data-callback = "bing" > Bing</ a >
5 < a href = "#" data-callback = "bang" > Bang</ a >
6 < a href = "#" > Bong</ a >
7 </ div >
8 < div class = "clearer" ></ div >
9 < div class = "divide" ></ div >
Wanted to keep it as simple as possible so that I/anyone can reuse this in any situation where there is a list. It easily manages and toggles selected. Even threw in some callback functionality. Feel free to make it better! :)
Here’s a demo: tabul8