Skip to content

Instantly share code, notes, and snippets.

@foo9
Created August 7, 2013 11:52
Show Gist options
  • Select an option

  • Save foo9/6173409 to your computer and use it in GitHub Desktop.

Select an option

Save foo9/6173409 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title></title>
<script type='text/javascript' src='http://code.jquery.com/jquery-git2.js'></script>
<style type='text/css'>
.selected {
background: #f00;
}
</style>
<script type='text/javascript'>
(function($, document) {
'use strict';
$.tabun = function($elements, options) {
var settings = $.extend({
keyCode: 9,
className: 'selected',
defalutIndex: 0
}, options);
var nextEvent = 'tabun.nextindex';
var currentIndex = settings.defalutIndex;
var enable = true;
var $doc = $(document);
var len = $elements.length;
$elements.each(function(index) {
$(this).attr('data-tabun-index', index);
});
$($elements[currentIndex]).addClass(settings.className);
$doc.on('keydown.tabun', function(e) {
var keyCode = e.keyCode || e.which;
if (enable && (keyCode === settings.keyCode)) {
e.preventDefault();
var $item = $elements.filter(function() {
return parseInt($(this).attr('data-tabun-index'), 10) === currentIndex;
});
if ($item.length) {
$($item[0]).removeClass(settings.className);
}
currentIndex = currentIndex + 1;
if (currentIndex >= len) {
currentIndex = 0;
}
$($elements[currentIndex]).addClass(settings.className);
}
});
return {
disable: function() {
enable = false;
},
enable: function() {
enable = true;
},
destroy: function() {
// TODO:
},
current: function(index) {
// TODO;
},
next: function() {
// TODO:
},
prev: function() {
// TODO:
}
};
};
})(jQuery, document);
// demo
$(function() {
var $items = $('#hoge li');
var options = {
defalutIndex: 3
};
var tabun = $.tabun($items, options);
$.tabun($('#fuga li'), {
keyCode: 32 // space key
});
});
</script>
</head>
<body>
<ul id="hoge">
<li>xxxxxx</li>
<li>xxxxxx</li>
<li>xxxxxx</li>
<li>xxxxxx</li>
</ul>
<ul id="fuga">
<li>xxxxxx</li>
<li>xxxxxx</li>
<li>xxxxxx</li>
<li>xxxxxx</li>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment