ff-range.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. html5slider - a JS implementation of <input type=range> for Firefox 16 and up
  3. https://github.com/fryn/html5slider
  4. Copyright (c) 2010-2013 Frank Yan, <http://frankyan.com>
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. */
  21. (function() {
  22. // test for native support
  23. var test = document.createElement('input');
  24. try {
  25. test.type = 'range';
  26. if (test.type == 'range')
  27. return;
  28. } catch (e) {
  29. return;
  30. }
  31. // test for required property support
  32. test.style.background = 'linear-gradient(red, red)';
  33. if (!test.style.backgroundImage || !('MozAppearance' in test.style))
  34. return;
  35. var scale;
  36. var isMac = navigator.platform == 'MacIntel';
  37. var thumb = {
  38. radius: isMac ? 9 : 6,
  39. width: isMac ? 22 : 12,
  40. height: isMac ? 16 : 20
  41. };
  42. var track = 'linear-gradient(transparent ' + (isMac ?
  43. '6px, #999 6px, #999 7px, #ccc 8px, #bbb 9px, #bbb 10px, transparent 10px' :
  44. '9px, #999 9px, #bbb 10px, #fff 11px, transparent 11px') +
  45. ', transparent)';
  46. var styles = {
  47. 'min-width': thumb.width + 'px',
  48. 'min-height': thumb.height + 'px',
  49. 'max-height': thumb.height + 'px',
  50. padding: '0 0 ' + (isMac ? '2px' : '1px'),
  51. border: 0,
  52. 'border-radius': 0,
  53. cursor: 'default',
  54. 'text-indent': '-999999px' // -moz-user-select: none; breaks mouse capture
  55. };
  56. var options = {
  57. attributes: true,
  58. attributeFilter: ['min', 'max', 'step', 'value']
  59. };
  60. var onInput = document.createEvent('HTMLEvents');
  61. onInput.initEvent('input', true, false);
  62. var onChange = document.createEvent('HTMLEvents');
  63. onChange.initEvent('change', true, false);
  64. if (document.readyState == 'loading')
  65. document.addEventListener('DOMContentLoaded', initialize, true);
  66. else
  67. initialize();
  68. addEventListener('pageshow', recreate, true);
  69. function initialize() {
  70. // create initial sliders
  71. recreate();
  72. // create sliders on-the-fly
  73. new MutationObserver(function(mutations) {
  74. mutations.forEach(function(mutation) {
  75. if (mutation.addedNodes)
  76. Array.forEach(mutation.addedNodes, function(node) {
  77. if (!(node instanceof Element))
  78. ;
  79. else if (node.childElementCount)
  80. Array.forEach(node.querySelectorAll('input[type=range]'), check);
  81. else if (node.mozMatchesSelector('input[type=range]'))
  82. check(node);
  83. });
  84. });
  85. }).observe(document, { childList: true, subtree: true });
  86. }
  87. function recreate() {
  88. Array.forEach(document.querySelectorAll('input[type=range]'), check);
  89. }
  90. function check(input) {
  91. if (input.type != 'range')
  92. transform(input);
  93. }
  94. function transform(slider) {
  95. var isValueSet, areAttrsSet, isUI, isClick, prevValue, rawValue, prevX;
  96. var min, max, step, range, value = slider.value;
  97. // lazily create shared slider affordance
  98. if (!scale) {
  99. scale = document.body.appendChild(document.createElement('hr'));
  100. style(scale, {
  101. '-moz-appearance': isMac ? 'scale-horizontal' : 'scalethumb-horizontal',
  102. display: 'block',
  103. visibility: 'visible',
  104. opacity: 1,
  105. position: 'fixed',
  106. top: '-999999px'
  107. });
  108. document.mozSetImageElement('__sliderthumb__', scale);
  109. }
  110. // reimplement value and type properties
  111. var getValue = function() { return '' + value; };
  112. var setValue = function setValue(val) {
  113. value = '' + val;
  114. isValueSet = true;
  115. draw();
  116. delete slider.value;
  117. slider.value = value;
  118. slider.__defineGetter__('value', getValue);
  119. slider.__defineSetter__('value', setValue);
  120. };
  121. slider.__defineGetter__('value', getValue);
  122. slider.__defineSetter__('value', setValue);
  123. Object.defineProperty(slider, 'type', {
  124. get: function() { return 'range'; }
  125. });
  126. // sync properties with attributes
  127. ['min', 'max', 'step'].forEach(function(name) {
  128. if (slider.hasAttribute(name))
  129. areAttrsSet = true;
  130. Object.defineProperty(slider, name, {
  131. get: function() {
  132. return this.hasAttribute(name) ? this.getAttribute(name) : '';
  133. },
  134. set: function(val) {
  135. val === null ?
  136. this.removeAttribute(name) :
  137. this.setAttribute(name, val);
  138. }
  139. });
  140. });
  141. // initialize slider
  142. slider.readOnly = true;
  143. style(slider, styles);
  144. update();
  145. new MutationObserver(function(mutations) {
  146. mutations.forEach(function(mutation) {
  147. if (mutation.attributeName != 'value') {
  148. update();
  149. areAttrsSet = true;
  150. }
  151. // note that value attribute only sets initial value
  152. else if (!isValueSet) {
  153. value = slider.getAttribute('value');
  154. draw();
  155. }
  156. });
  157. }).observe(slider, options);
  158. slider.addEventListener('mousedown', onDragStart, true);
  159. slider.addEventListener('keydown', onKeyDown, true);
  160. slider.addEventListener('focus', onFocus, true);
  161. slider.addEventListener('blur', onBlur, true);
  162. function onDragStart(e) {
  163. isClick = true;
  164. setTimeout(function() { isClick = false; }, 0);
  165. if (e.button || !range)
  166. return;
  167. var width = parseFloat(getComputedStyle(this).width);
  168. var multiplier = (width - thumb.width) / range;
  169. if (!multiplier)
  170. return;
  171. // distance between click and center of thumb
  172. var dev = e.clientX - this.getBoundingClientRect().left - thumb.width / 2 -
  173. (value - min) * multiplier;
  174. // if click was not on thumb, move thumb to click location
  175. if (Math.abs(dev) > thumb.radius) {
  176. isUI = true;
  177. this.value -= -dev / multiplier;
  178. }
  179. rawValue = value;
  180. prevX = e.clientX;
  181. this.addEventListener('mousemove', onDrag, true);
  182. this.addEventListener('mouseup', onDragEnd, true);
  183. }
  184. function onDrag(e) {
  185. var width = parseFloat(getComputedStyle(this).width);
  186. var multiplier = (width - thumb.width) / range;
  187. if (!multiplier)
  188. return;
  189. rawValue += (e.clientX - prevX) / multiplier;
  190. prevX = e.clientX;
  191. isUI = true;
  192. this.value = rawValue;
  193. }
  194. function onDragEnd() {
  195. this.removeEventListener('mousemove', onDrag, true);
  196. this.removeEventListener('mouseup', onDragEnd, true);
  197. slider.dispatchEvent(onInput);
  198. slider.dispatchEvent(onChange);
  199. }
  200. function onKeyDown(e) {
  201. if (e.keyCode > 36 && e.keyCode < 41) { // 37-40: left, up, right, down
  202. onFocus.call(this);
  203. isUI = true;
  204. this.value = value + (e.keyCode == 38 || e.keyCode == 39 ? step : -step);
  205. }
  206. }
  207. function onFocus() {
  208. if (!isClick)
  209. this.style.boxShadow = !isMac ? '0 0 0 2px #fb0' :
  210. 'inset 0 0 20px rgba(0,127,255,.1), 0 0 1px rgba(0,127,255,.4)';
  211. }
  212. function onBlur() {
  213. this.style.boxShadow = '';
  214. }
  215. // determines whether value is valid number in attribute form
  216. function isAttrNum(value) {
  217. return !isNaN(value) && +value == parseFloat(value);
  218. }
  219. // validates min, max, and step attributes and redraws
  220. function update() {
  221. min = isAttrNum(slider.min) ? +slider.min : 0;
  222. max = isAttrNum(slider.max) ? +slider.max : 100;
  223. if (max < min)
  224. max = min > 100 ? min : 100;
  225. step = isAttrNum(slider.step) && slider.step > 0 ? +slider.step : 1;
  226. range = max - min;
  227. draw(true);
  228. }
  229. // recalculates value property
  230. function calc() {
  231. if (!isValueSet && !areAttrsSet)
  232. value = slider.getAttribute('value');
  233. if (!isAttrNum(value))
  234. value = (min + max) / 2;;
  235. // snap to step intervals (WebKit sometimes does not - bug?)
  236. value = Math.round((value - min) / step) * step + min;
  237. if (value < min)
  238. value = min;
  239. else if (value > max)
  240. value = min + ~~(range / step) * step;
  241. }
  242. // renders slider using CSS background ;)
  243. function draw(attrsModified) {
  244. calc();
  245. var wasUI = isUI;
  246. isUI = false;
  247. if (wasUI && value != prevValue)
  248. slider.dispatchEvent(onInput);
  249. if (!attrsModified && value == prevValue)
  250. return;
  251. prevValue = value;
  252. var position = range ? (value - min) / range * 100 : 0;
  253. var bg = '-moz-element(#__sliderthumb__) ' + position + '% no-repeat, ';
  254. style(slider, { background: bg + track });
  255. }
  256. }
  257. function style(element, styles) {
  258. for (var prop in styles)
  259. element.style.setProperty(prop, styles[prop], 'important');
  260. }
  261. })();