Skip to content

Instantly share code, notes, and snippets.

@cherifGsoul
Created September 12, 2013 14:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cherifGsoul/6538931 to your computer and use it in GitHub Desktop.
Save cherifGsoul/6538931 to your computer and use it in GitHub Desktop.
Twitter Bootstrap tabs with canjs Control and Routing
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
</head>
<body>
<div class="container">
<ul class="nav nav-tabs" id="myTab">
<li class="active"><a href="#home">Home</a></li>
<li><a href="#profile">Profile</a></li>
<li><a href="#messages">Messages</a></li>
<li><a href="#settings">Settings</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="home">Home</div>
<div class="tab-pane" id="profile">Profile</div>
<div class="tab-pane" id="messages">Messages</div>
<div class="tab-pane" id="settings">Settings</div>
</div>
</div>
<script type="text/javascript" src="js/jquery.1.9.1.js"></script>
<script type="text/javascript" src="js/can.jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
var Tabs=can.Control({
init:function(){
var tab = this.tab;
this.element.children( 'li' ).each(function() {
tab( $( this ) ).hide();
});
},
// helper function finds the tab for a given li
tab: function( li ) {
return $( li.find( 'a' ).attr( 'href' ) );
},
"{can.route} {attr}" : function(route, ev, newVal, oldVal){
this.activate(newVal,oldVal);
},
button : function(id){
// if nothing is active, activate the first
return id ? this.element.find("a[href=#"+id+"]").parent() :
this.element.children( 'li:first' );
},
activate: function( active, oldActive ){
// deactivate the old active
var oldButton = this.button(oldActive).removeClass('active');
this.tab(oldButton).hide();
// activate new
var newButton = this.button(active).addClass('active');
this.tab(newButton).show();
},
'li click':function(el,ev){
ev.preventDefault();
can.route.attr(this.options.attr,this.tab(el)[0].id);
}
})
can.route(':tab',{tab:'home'});
new Tabs('#myTab',{attr:'tab'});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment