fuelux.spinner.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. /*
  2. * Fuel UX Spinbox
  3. * https://github.com/ExactTarget/fuelux
  4. *
  5. * Copyright (c) 2014 ExactTarget
  6. * Licensed under the BSD New license.
  7. */
  8. // -- BEGIN UMD WRAPPER PREFACE --
  9. // For more information on UMD visit:
  10. // https://github.com/umdjs/umd/blob/master/jqueryPlugin.js
  11. (function (factory) {
  12. if (typeof define === 'function' && define.amd) {
  13. // if AMD loader is available, register as an anonymous module.
  14. define(['jquery'], factory);
  15. } else {
  16. // OR use browser globals if AMD is not present
  17. factory(jQuery);
  18. }
  19. }(function ($, undefined) {
  20. // -- END UMD WRAPPER PREFACE --
  21. // -- BEGIN MODULE CODE HERE --
  22. var old = $.fn.spinbox;
  23. // SPINBOX CONSTRUCTOR AND PROTOTYPE
  24. var Spinbox = function (element, options) {
  25. this.$element = $(element);
  26. this.options = $.extend({}, $.fn.spinbox.defaults, options);
  27. this.$input = this.$element.find('.spinbox-input');
  28. this.$element.on('focusin.fu.spinbox', this.$input, $.proxy(this.changeFlag, this));
  29. this.$element.on('focusout.fu.spinbox', this.$input, $.proxy(this.change, this));
  30. this.$element.on('keydown.fu.spinbox', this.$input, $.proxy(this.keydown, this));
  31. this.$element.on('keyup.fu.spinbox', this.$input, $.proxy(this.keyup, this));
  32. this.bindMousewheelListeners();
  33. this.mousewheelTimeout = {};
  34. if (this.options.hold) {
  35. this.$element.on('mousedown.fu.spinbox', '.spinbox-up', $.proxy(function() { this.startSpin(true); } , this));
  36. this.$element.on('mouseup.fu.spinbox', '.spinbox-up, .spinbox-down', $.proxy(this.stopSpin, this));
  37. this.$element.on('mouseout.fu.spinbox', '.spinbox-up, .spinbox-down', $.proxy(this.stopSpin, this));
  38. this.$element.on('mousedown.fu.spinbox', '.spinbox-down', $.proxy(function() {this.startSpin(false);} , this));
  39. } else {
  40. this.$element.on('click.fu.spinbox', '.spinbox-up', $.proxy(function() { this.step(true); } , this));
  41. this.$element.on('click.fu.spinbox', '.spinbox-down', $.proxy(function() { this.step(false); }, this));
  42. }
  43. this.switches = {
  44. count: 1,
  45. enabled: true
  46. };
  47. if (this.options.speed === 'medium') {
  48. this.switches.speed = 300;
  49. } else if (this.options.speed === 'fast') {
  50. this.switches.speed = 100;
  51. } else {
  52. this.switches.speed = 500;
  53. }
  54. this.lastValue = this.options.value;
  55. this.render();
  56. if (this.options.disabled) {
  57. this.disable();
  58. }
  59. };
  60. Spinbox.prototype = {
  61. constructor: Spinbox,
  62. destroy: function() {
  63. this.$element.remove();
  64. // any external bindings
  65. // [none]
  66. // set input value attrbute
  67. this.$element.find('input').each(function() {
  68. $(this).attr('value', $(this).val());
  69. });
  70. // empty elements to return to original markup
  71. // [none]
  72. // returns string of markup
  73. return this.$element[0].outerHTML;
  74. },
  75. render: function () {
  76. var inputValue = this.parseInput( this.$input.val() );
  77. var maxUnitLength = '';
  78. // if input is empty and option value is default, 0
  79. if (inputValue !== '' && this.options.value === 0) {
  80. this.value(inputValue);
  81. } else {
  82. this.output ( this.options.value );
  83. }
  84. if ( this.options.units.length ) {
  85. $.each(this.options.units, function(index, value){
  86. if( value.length > maxUnitLength.length) {
  87. maxUnitLength = value;
  88. }
  89. });
  90. }
  91. },
  92. output: function(value, updateField) {
  93. value = (value + '').split('.').join(this.options.decimalMark);
  94. updateField = ( updateField || true );
  95. if ( updateField ) { this.$input.val(value); }
  96. return value;
  97. },
  98. parseInput: function(value) {
  99. value = (value + '').split(this.options.decimalMark).join('.');
  100. return value;
  101. },
  102. change: function () {
  103. var newVal = this.parseInput( this.$input.val() ) || '';
  104. if(this.options.units.length || this.options.decimalMark !== '.'){
  105. newVal = this.parseValueWithUnit(newVal);
  106. } else if (newVal/1){
  107. newVal = this.options.value = this.checkMaxMin(newVal/1);
  108. } else {
  109. newVal = this.checkMaxMin(newVal.replace(/[^0-9.-]/g,'') || '');
  110. this.options.value = newVal/1;
  111. }
  112. this.output ( newVal );
  113. this.changeFlag = false;
  114. this.triggerChangedEvent();
  115. },
  116. changeFlag: function(){
  117. this.changeFlag = true;
  118. },
  119. stopSpin: function () {
  120. if(this.switches.timeout!==undefined){
  121. clearTimeout(this.switches.timeout);
  122. this.switches.count = 1;
  123. this.triggerChangedEvent();
  124. }
  125. },
  126. triggerChangedEvent: function () {
  127. var currentValue = this.value();
  128. if (currentValue === this.lastValue) return;
  129. this.lastValue = currentValue;
  130. // Primary changed event
  131. this.$element.trigger('changed.fu.spinbox', this.output(currentValue, false)); // no DOM update
  132. },
  133. startSpin: function (type) {
  134. if (!this.options.disabled) {
  135. var divisor = this.switches.count;
  136. if (divisor === 1) {
  137. this.step(type);
  138. divisor = 1;
  139. } else if (divisor < 3){
  140. divisor = 1.5;
  141. } else if (divisor < 8){
  142. divisor = 2.5;
  143. } else {
  144. divisor = 4;
  145. }
  146. this.switches.timeout = setTimeout($.proxy(function() {this.iterate(type);} ,this),this.switches.speed/divisor);
  147. this.switches.count++;
  148. }
  149. },
  150. iterate: function (type) {
  151. this.step(type);
  152. this.startSpin(type);
  153. },
  154. step: function (isIncrease) {
  155. // isIncrease: true is up, false is down
  156. var digits, multiple, currentValue, limitValue;
  157. // trigger change event
  158. if( this.changeFlag ) {
  159. this.change();
  160. }
  161. // get current value and min/max options
  162. currentValue = this.options.value;
  163. limitValue = isIncrease ? this.options.max : this.options.min;
  164. if ((isIncrease ? currentValue < limitValue : currentValue > limitValue)) {
  165. var newVal = currentValue + (isIncrease ? 1 : -1) * this.options.step;
  166. // raise to power of 10 x number of decimal places, then round
  167. if(this.options.step % 1 !== 0){
  168. digits = (this.options.step + '').split('.')[1].length;
  169. multiple = Math.pow(10, digits);
  170. newVal = Math.round(newVal * multiple) / multiple;
  171. }
  172. // if outside limits, set to limit value
  173. if (isIncrease ? newVal > limitValue : newVal < limitValue) {
  174. this.value(limitValue);
  175. }
  176. else {
  177. this.value(newVal);
  178. }
  179. }
  180. else if (this.options.cycle) {
  181. var cycleVal = isIncrease ? this.options.min : this.options.max;
  182. this.value(cycleVal);
  183. }
  184. },
  185. value: function (value) {
  186. if ( value || value === 0 ) {
  187. if( this.options.units.length || this.options.decimalMark !== '.' ) {
  188. this.output( this.parseValueWithUnit( value + (this.unit || '') ) );
  189. return this;
  190. } else if ( !isNaN(parseFloat(value)) && isFinite(value) ) {
  191. this.options.value = value/1;
  192. this.output ( value + (this.unit ? this.unit : '') ) ;
  193. return this;
  194. }
  195. } else {
  196. if( this.changeFlag ) {
  197. this.change();
  198. }
  199. if( this.unit ){
  200. return this.options.value + this.unit;
  201. } else {
  202. return this.output(this.options.value, false); // no DOM update
  203. }
  204. }
  205. },
  206. isUnitLegal: function (unit) {
  207. var legalUnit;
  208. $.each(this.options.units, function(index, value){
  209. if( value.toLowerCase() === unit.toLowerCase()){
  210. legalUnit = unit.toLowerCase();
  211. return false;
  212. }
  213. });
  214. return legalUnit;
  215. },
  216. // strips units and add them back
  217. parseValueWithUnit: function( value ){
  218. var unit = value.replace(/[^a-zA-Z]/g,'');
  219. var number = value.replace(/[^0-9.-]/g,'');
  220. if(unit){
  221. unit = this.isUnitLegal(unit);
  222. }
  223. this.options.value = this.checkMaxMin(number/1);
  224. this.unit = unit || undefined;
  225. return this.options.value + (unit || '');
  226. },
  227. checkMaxMin: function(value){
  228. // if unreadable
  229. if ( isNaN( parseFloat(value) ) ) {
  230. return value;
  231. }
  232. // if not within range return the limit
  233. if ( !( value <= this.options.max && value >= this.options.min ) ){
  234. value = value >= this.options.max ? this.options.max : this.options.min;
  235. }
  236. return value;
  237. },
  238. disable: function () {
  239. this.options.disabled = true;
  240. this.$element.addClass('disabled');
  241. this.$input.attr('disabled','');
  242. this.$element.find('button').addClass('disabled');
  243. },
  244. enable: function () {
  245. this.options.disabled = false;
  246. this.$element.removeClass('disabled');
  247. this.$input.removeAttr("disabled");
  248. this.$element.find('button').removeClass('disabled');
  249. },
  250. keydown: function(event){
  251. var keyCode = event.keyCode;
  252. if(keyCode===38){
  253. this.step(true);
  254. }else if(keyCode===40){
  255. this.step(false);
  256. }
  257. },
  258. keyup: function(event){
  259. var keyCode = event.keyCode;
  260. if(keyCode===38 || keyCode===40){
  261. this.triggerChangedEvent();
  262. }
  263. },
  264. bindMousewheelListeners: function(){
  265. var inputEl = this.$input.get(0);
  266. if(inputEl.addEventListener){
  267. //IE 9, Chrome, Safari, Opera
  268. inputEl.addEventListener('mousewheel', $.proxy(this.mousewheelHandler, this), false);
  269. // Firefox
  270. inputEl.addEventListener('DOMMouseScroll', $.proxy(this.mousewheelHandler, this), false);
  271. }else{
  272. // IE <9
  273. inputEl.attachEvent('onmousewheel', $.proxy(this.mousewheelHandler, this));
  274. }
  275. },
  276. mousewheelHandler: function(event){
  277. var e = window.event || event; // old IE support
  278. var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
  279. var self = this;
  280. clearTimeout(this.mousewheelTimeout);
  281. this.mousewheelTimeout = setTimeout(function(){
  282. self.triggerChangedEvent();
  283. }, 300);
  284. if(delta>0){//ACE
  285. this.step(true);
  286. }else{
  287. this.step(false);
  288. }
  289. if(e.preventDefault){
  290. e.preventDefault();
  291. }else{
  292. e.returnValue = false;
  293. }
  294. return false;
  295. }
  296. };
  297. // SPINBOX PLUGIN DEFINITION
  298. $.fn.spinbox = function (option) {
  299. var args = Array.prototype.slice.call( arguments, 1 );
  300. var methodReturn;
  301. var $set = this.each(function () {
  302. var $this = $( this );
  303. var data = $this.data('fu.spinbox');
  304. var options = typeof option === 'object' && option;
  305. if( !data ) {
  306. $this.data('fu.spinbox', (data = new Spinbox( this, options ) ) );
  307. }
  308. if( typeof option === 'string' ) {
  309. methodReturn = data[ option ].apply( data, args );
  310. }
  311. });
  312. return ( methodReturn === undefined ) ? $set : methodReturn;
  313. };
  314. // value needs to be 0 for this.render();
  315. $.fn.spinbox.defaults = {
  316. value: 0,
  317. min: 0,
  318. max: 999,
  319. step: 1,
  320. hold: true,
  321. speed: 'medium',
  322. disabled: false,
  323. cycle: false,
  324. units: [],
  325. decimalMark: '.'
  326. };
  327. $.fn.spinbox.Constructor = Spinbox;
  328. $.fn.spinbox.noConflict = function () {
  329. $.fn.spinbox = old;
  330. return this;
  331. };
  332. // DATA-API
  333. $(document).on('mousedown.fu.spinbox.data-api', '[data-initialize=spinbox]', function (e) {
  334. var $control = $(e.target).closest('.spinbox');
  335. if ( !$control.data('fu.spinbox') ) {
  336. $control.spinbox($control.data());
  337. }
  338. });
  339. // Must be domReady for AMD compatibility
  340. $(function () {
  341. $('[data-initialize=spinbox]').each(function () {
  342. var $this = $(this);
  343. if (!$this.data('fu.spinbox')) {
  344. $this.spinbox($this.data());
  345. }
  346. });
  347. });
  348. // -- BEGIN UMD WRAPPER AFTERWORD --
  349. }));
  350. // -- END UMD WRAPPER AFTERWORD --