spinbox.js 11 KB

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