-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathjquery-dropdown-dot.min.js
8 lines (8 loc) · 2.32 KB
/
jquery-dropdown-dot.min.js
1
2
3
4
5
6
7
8
/**
* dropdown.dot.js
*
* A super-flexible and clean JQuery Dropdown Plugin based on dot.js Templates.
*
* @author Roger Dudler <[email protected]>
*/
(function($){$.fn.dropdown=function(p){var q=$.extend({'selected':'.selected','items':'ul','item':'li','openClass':'open','changed':function(a){}},p);return this.each(function(){var h=$(this);h.hide();var i=doT.template($(h.data('template')).text());var j=doT.template($(h.data('template')+'-selected').text());var k={"selected":null,"items":[],"classes":h.data('classes')};var l=0;$.each(h.find('option'),function(c,d){var e=$(d);var f={'value':e.attr('value'),'label':e.text(),'selected':e.is(':selected')};var g=e.data();$.each(g,function(a,b){f[a]=b});if(e.is(':selected')){k.selected=f;l=c}k.items.push(f)});var m=$(i(k));var n=m.find(q.items);var o=m.find('> '+q.selected);o.on('mousedown',function(){m.focus();if(n.is(':visible')){_closeDropdown()}else{_openDropdown()}return false});m.on('focus',function(){h.addClass('focus')});m.on('blur',function(){h.removeClass('focus');_closeDropdown()});m.on('keydown',function(e){var a=null;switch(e.keyCode){case 40:if(!m.hasClass(q.openClass)){_openDropdown();a=n.find('.selected')}else{a=n.find('.hover').next(q.item).first();if(!a.length){a=n.find(q.item).first()}}_selectItem(a,true);e.preventDefault();break;case 38:if(!m.hasClass(q.openClass)){_openDropdown();a=n.find('.selected')}else{a=n.find('.hover').prev(q.item).first();if(!a.length){a=n.find(q.item).last()}}_selectItem(a,true);e.preventDefault();break;case 13:if(!m.hasClass(q.openClass)){_openDropdown()}else{var b=n.find('.hover').first();if(b){_chooseItem(b)}}e.preventDefault();break}});n.find('[data-index='+l+']').addClass('selected');n.on('mousedown',q.item,function(){_chooseItem(this);return false});n.on('mouseover',q.item,function(){_selectItem(this,false)});function _selectItem(a,b){var c=$(a);n.find(q.item).removeClass('hover');c.addClass('hover');if(b){c.parent().scrollTop(c.position().top-c.height())}}function _chooseItem(a){var b=$(a).data('index');var c=k.items[b];m.find('> '+q.selected).html(j(c));n.find('[data-index='+l+']').removeClass('selected');l=b;$(a).addClass('selected');h.val(c.value);q.changed(c);_closeDropdown()}function _openDropdown(){n.show();m.addClass(q.openClass)}function _closeDropdown(){n.hide();m.removeClass(q.openClass)}return h.before(m)})}})(jQuery);