jQuery on and Delegate
Blogs20142014-11-13
jQuery on and Delegate
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>jQuery on and Delegate</title>
<link href="../bower_components/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
<style>
div#tabContents div {
display: none;
}
div#tabContents div.active {
display: block;
}
</style>
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<!--<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>-->
</head>
<body>
<div class="container">
<h2>jQuery on and Delegate</h2>
<div class="row">
<ul id="tabs" class="nav nav-tabs">
<li data-tab="home"><a href="#">Home</a></li>
<li data-tab="about"><a href="#">About</a></li>
<li data-tab="contact"><a href="#">Contact</a></li>
</ul>
</div>
<div class="row">
<div id="tabContents">
<div data-content="home">Home</div>
<div data-content="about">About</div>
<div data-content="contact">Contact</div>
</div>
</div>
</div>
<script>
(function() {
jQuery.fn.tabs = function(content) {
var that = this;
$(that).on('click', 'li', function() {
var tabName = $(this).data('tab');
$(that).trigger('change.tab', tabName);
});
$(that).bind('change.tab', function(e, tabName) {
if(!tabName) tabName = $(that).find('li:first').data('tab');
$(that).find('li').removeClass('active');
$(that).find('>[data-tab="' + tabName + '"]').addClass('active');
$(content).find('>[data-content]').removeClass('active');
$(content).find('>[data-content="' + tabName + '"]').addClass('active');
});
var firstName = $(that).find('li:first').data('tab');
$(that).trigger('change.tab', firstName);
return that;
}
$(function() {
$('ul#tabs').tabs('#tabContents');
// $('ul#tabs').bind('change.tab', function(e, tabName) {
// //debugger;
// window.location.hash = tabName;
// console.log('1', tabName, window.location.hash, typeof window.location.hash);
// });
// $(window).bind('hashchange', function() {
// var tabName = window.location.hash.slice(1);
// console.log('2', tabName, window.location.hash, typeof window.location.hash);
// //$('#tabs').trigger('change.tab', tabName);
// });
});
}());
</script>
</body>
</html>