nouislider.js 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959
  1. /*! nouislider - 8.5.1 - 2016-04-24 16:00:29 */
  2. (function (factory) {
  3. if ( typeof define === 'function' && define.amd ) {
  4. // AMD. Register as an anonymous module.
  5. define([], factory);
  6. } else if ( typeof exports === 'object' ) {
  7. // Node/CommonJS
  8. module.exports = factory();
  9. } else {
  10. // Browser globals
  11. window.noUiSlider = factory();
  12. }
  13. }(function( ){
  14. 'use strict';
  15. // Removes duplicates from an array.
  16. function unique(array) {
  17. return array.filter(function(a){
  18. return !this[a] ? this[a] = true : false;
  19. }, {});
  20. }
  21. // Round a value to the closest 'to'.
  22. function closest ( value, to ) {
  23. return Math.round(value / to) * to;
  24. }
  25. // Current position of an element relative to the document.
  26. function offset ( elem ) {
  27. var rect = elem.getBoundingClientRect(),
  28. doc = elem.ownerDocument,
  29. docElem = doc.documentElement,
  30. pageOffset = getPageOffset();
  31. // getBoundingClientRect contains left scroll in Chrome on Android.
  32. // I haven't found a feature detection that proves this. Worst case
  33. // scenario on mis-match: the 'tap' feature on horizontal sliders breaks.
  34. if ( /webkit.*Chrome.*Mobile/i.test(navigator.userAgent) ) {
  35. pageOffset.x = 0;
  36. }
  37. return {
  38. top: rect.top + pageOffset.y - docElem.clientTop,
  39. left: rect.left + pageOffset.x - docElem.clientLeft
  40. };
  41. }
  42. // Checks whether a value is numerical.
  43. function isNumeric ( a ) {
  44. return typeof a === 'number' && !isNaN( a ) && isFinite( a );
  45. }
  46. // Sets a class and removes it after [duration] ms.
  47. function addClassFor ( element, className, duration ) {
  48. addClass(element, className);
  49. setTimeout(function(){
  50. removeClass(element, className);
  51. }, duration);
  52. }
  53. // Limits a value to 0 - 100
  54. function limit ( a ) {
  55. return Math.max(Math.min(a, 100), 0);
  56. }
  57. // Wraps a variable as an array, if it isn't one yet.
  58. function asArray ( a ) {
  59. return Array.isArray(a) ? a : [a];
  60. }
  61. // Counts decimals
  62. function countDecimals ( numStr ) {
  63. var pieces = numStr.split(".");
  64. return pieces.length > 1 ? pieces[1].length : 0;
  65. }
  66. // http://youmightnotneedjquery.com/#add_class
  67. function addClass ( el, className ) {
  68. if ( el.classList ) {
  69. el.classList.add(className);
  70. } else {
  71. el.className += ' ' + className;
  72. }
  73. }
  74. // http://youmightnotneedjquery.com/#remove_class
  75. function removeClass ( el, className ) {
  76. if ( el.classList ) {
  77. el.classList.remove(className);
  78. } else {
  79. el.className = el.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
  80. }
  81. }
  82. // https://plainjs.com/javascript/attributes/adding-removing-and-testing-for-classes-9/
  83. function hasClass ( el, className ) {
  84. return el.classList ? el.classList.contains(className) : new RegExp('\\b' + className + '\\b').test(el.className);
  85. }
  86. // https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes
  87. function getPageOffset ( ) {
  88. var supportPageOffset = window.pageXOffset !== undefined,
  89. isCSS1Compat = ((document.compatMode || "") === "CSS1Compat"),
  90. x = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft,
  91. y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
  92. return {
  93. x: x,
  94. y: y
  95. };
  96. }
  97. // we provide a function to compute constants instead
  98. // of accessing window.* as soon as the module needs it
  99. // so that we do not compute anything if not needed
  100. function getActions ( ) {
  101. // Determine the events to bind. IE11 implements pointerEvents without
  102. // a prefix, which breaks compatibility with the IE10 implementation.
  103. return window.navigator.pointerEnabled ? {
  104. start: 'pointerdown',
  105. move: 'pointermove',
  106. end: 'pointerup'
  107. } : window.navigator.msPointerEnabled ? {
  108. start: 'MSPointerDown',
  109. move: 'MSPointerMove',
  110. end: 'MSPointerUp'
  111. } : {
  112. start: 'mousedown touchstart',
  113. move: 'mousemove touchmove',
  114. end: 'mouseup touchend'
  115. };
  116. }
  117. // Value calculation
  118. // Determine the size of a sub-range in relation to a full range.
  119. function subRangeRatio ( pa, pb ) {
  120. return (100 / (pb - pa));
  121. }
  122. // (percentage) How many percent is this value of this range?
  123. function fromPercentage ( range, value ) {
  124. return (value * 100) / ( range[1] - range[0] );
  125. }
  126. // (percentage) Where is this value on this range?
  127. function toPercentage ( range, value ) {
  128. return fromPercentage( range, range[0] < 0 ?
  129. value + Math.abs(range[0]) :
  130. value - range[0] );
  131. }
  132. // (value) How much is this percentage on this range?
  133. function isPercentage ( range, value ) {
  134. return ((value * ( range[1] - range[0] )) / 100) + range[0];
  135. }
  136. // Range conversion
  137. function getJ ( value, arr ) {
  138. var j = 1;
  139. while ( value >= arr[j] ){
  140. j += 1;
  141. }
  142. return j;
  143. }
  144. // (percentage) Input a value, find where, on a scale of 0-100, it applies.
  145. function toStepping ( xVal, xPct, value ) {
  146. if ( value >= xVal.slice(-1)[0] ){
  147. return 100;
  148. }
  149. var j = getJ( value, xVal ), va, vb, pa, pb;
  150. va = xVal[j-1];
  151. vb = xVal[j];
  152. pa = xPct[j-1];
  153. pb = xPct[j];
  154. return pa + (toPercentage([va, vb], value) / subRangeRatio (pa, pb));
  155. }
  156. // (value) Input a percentage, find where it is on the specified range.
  157. function fromStepping ( xVal, xPct, value ) {
  158. // There is no range group that fits 100
  159. if ( value >= 100 ){
  160. return xVal.slice(-1)[0];
  161. }
  162. var j = getJ( value, xPct ), va, vb, pa, pb;
  163. va = xVal[j-1];
  164. vb = xVal[j];
  165. pa = xPct[j-1];
  166. pb = xPct[j];
  167. return isPercentage([va, vb], (value - pa) * subRangeRatio (pa, pb));
  168. }
  169. // (percentage) Get the step that applies at a certain value.
  170. function getStep ( xPct, xSteps, snap, value ) {
  171. if ( value === 100 ) {
  172. return value;
  173. }
  174. var j = getJ( value, xPct ), a, b;
  175. // If 'snap' is set, steps are used as fixed points on the slider.
  176. if ( snap ) {
  177. a = xPct[j-1];
  178. b = xPct[j];
  179. // Find the closest position, a or b.
  180. if ((value - a) > ((b-a)/2)){
  181. return b;
  182. }
  183. return a;
  184. }
  185. if ( !xSteps[j-1] ){
  186. return value;
  187. }
  188. return xPct[j-1] + closest(
  189. value - xPct[j-1],
  190. xSteps[j-1]
  191. );
  192. }
  193. // Entry parsing
  194. function handleEntryPoint ( index, value, that ) {
  195. var percentage;
  196. // Wrap numerical input in an array.
  197. if ( typeof value === "number" ) {
  198. value = [value];
  199. }
  200. // Reject any invalid input, by testing whether value is an array.
  201. if ( Object.prototype.toString.call( value ) !== '[object Array]' ){
  202. throw new Error("noUiSlider: 'range' contains invalid value.");
  203. }
  204. // Covert min/max syntax to 0 and 100.
  205. if ( index === 'min' ) {
  206. percentage = 0;
  207. } else if ( index === 'max' ) {
  208. percentage = 100;
  209. } else {
  210. percentage = parseFloat( index );
  211. }
  212. // Check for correct input.
  213. if ( !isNumeric( percentage ) || !isNumeric( value[0] ) ) {
  214. throw new Error("noUiSlider: 'range' value isn't numeric.");
  215. }
  216. // Store values.
  217. that.xPct.push( percentage );
  218. that.xVal.push( value[0] );
  219. // NaN will evaluate to false too, but to keep
  220. // logging clear, set step explicitly. Make sure
  221. // not to override the 'step' setting with false.
  222. if ( !percentage ) {
  223. if ( !isNaN( value[1] ) ) {
  224. that.xSteps[0] = value[1];
  225. }
  226. } else {
  227. that.xSteps.push( isNaN(value[1]) ? false : value[1] );
  228. }
  229. }
  230. function handleStepPoint ( i, n, that ) {
  231. // Ignore 'false' stepping.
  232. if ( !n ) {
  233. return true;
  234. }
  235. // Factor to range ratio
  236. that.xSteps[i] = fromPercentage([
  237. that.xVal[i]
  238. ,that.xVal[i+1]
  239. ], n) / subRangeRatio (
  240. that.xPct[i],
  241. that.xPct[i+1] );
  242. }
  243. // Interface
  244. // The interface to Spectrum handles all direction-based
  245. // conversions, so the above values are unaware.
  246. function Spectrum ( entry, snap, direction, singleStep ) {
  247. this.xPct = [];
  248. this.xVal = [];
  249. this.xSteps = [ singleStep || false ];
  250. this.xNumSteps = [ false ];
  251. this.snap = snap;
  252. this.direction = direction;
  253. var index, ordered = [ /* [0, 'min'], [1, '50%'], [2, 'max'] */ ];
  254. // Map the object keys to an array.
  255. for ( index in entry ) {
  256. if ( entry.hasOwnProperty(index) ) {
  257. ordered.push([entry[index], index]);
  258. }
  259. }
  260. // Sort all entries by value (numeric sort).
  261. if ( ordered.length && typeof ordered[0][0] === "object" ) {
  262. ordered.sort(function(a, b) { return a[0][0] - b[0][0]; });
  263. } else {
  264. ordered.sort(function(a, b) { return a[0] - b[0]; });
  265. }
  266. // Convert all entries to subranges.
  267. for ( index = 0; index < ordered.length; index++ ) {
  268. handleEntryPoint(ordered[index][1], ordered[index][0], this);
  269. }
  270. // Store the actual step values.
  271. // xSteps is sorted in the same order as xPct and xVal.
  272. this.xNumSteps = this.xSteps.slice(0);
  273. // Convert all numeric steps to the percentage of the subrange they represent.
  274. for ( index = 0; index < this.xNumSteps.length; index++ ) {
  275. handleStepPoint(index, this.xNumSteps[index], this);
  276. }
  277. }
  278. Spectrum.prototype.getMargin = function ( value ) {
  279. return this.xPct.length === 2 ? fromPercentage(this.xVal, value) : false;
  280. };
  281. Spectrum.prototype.toStepping = function ( value ) {
  282. value = toStepping( this.xVal, this.xPct, value );
  283. // Invert the value if this is a right-to-left slider.
  284. if ( this.direction ) {
  285. value = 100 - value;
  286. }
  287. return value;
  288. };
  289. Spectrum.prototype.fromStepping = function ( value ) {
  290. // Invert the value if this is a right-to-left slider.
  291. if ( this.direction ) {
  292. value = 100 - value;
  293. }
  294. return fromStepping( this.xVal, this.xPct, value );
  295. };
  296. Spectrum.prototype.getStep = function ( value ) {
  297. // Find the proper step for rtl sliders by search in inverse direction.
  298. // Fixes issue #262.
  299. if ( this.direction ) {
  300. value = 100 - value;
  301. }
  302. value = getStep(this.xPct, this.xSteps, this.snap, value );
  303. if ( this.direction ) {
  304. value = 100 - value;
  305. }
  306. return value;
  307. };
  308. Spectrum.prototype.getApplicableStep = function ( value ) {
  309. // If the value is 100%, return the negative step twice.
  310. var j = getJ(value, this.xPct), offset = value === 100 ? 2 : 1;
  311. return [this.xNumSteps[j-2], this.xVal[j-offset], this.xNumSteps[j-offset]];
  312. };
  313. // Outside testing
  314. Spectrum.prototype.convert = function ( value ) {
  315. return this.getStep(this.toStepping(value));
  316. };
  317. /* Every input option is tested and parsed. This'll prevent
  318. endless validation in internal methods. These tests are
  319. structured with an item for every option available. An
  320. option can be marked as required by setting the 'r' flag.
  321. The testing function is provided with three arguments:
  322. - The provided value for the option;
  323. - A reference to the options object;
  324. - The name for the option;
  325. The testing function returns false when an error is detected,
  326. or true when everything is OK. It can also modify the option
  327. object, to make sure all values can be correctly looped elsewhere. */
  328. var defaultFormatter = { 'to': function( value ){
  329. return value !== undefined && value.toFixed(2);
  330. }, 'from': Number };
  331. function testStep ( parsed, entry ) {
  332. if ( !isNumeric( entry ) ) {
  333. throw new Error("noUiSlider: 'step' is not numeric.");
  334. }
  335. // The step option can still be used to set stepping
  336. // for linear sliders. Overwritten if set in 'range'.
  337. parsed.singleStep = entry;
  338. }
  339. function testRange ( parsed, entry ) {
  340. // Filter incorrect input.
  341. if ( typeof entry !== 'object' || Array.isArray(entry) ) {
  342. throw new Error("noUiSlider: 'range' is not an object.");
  343. }
  344. // Catch missing start or end.
  345. if ( entry.min === undefined || entry.max === undefined ) {
  346. throw new Error("noUiSlider: Missing 'min' or 'max' in 'range'.");
  347. }
  348. // Catch equal start or end.
  349. if ( entry.min === entry.max ) {
  350. throw new Error("noUiSlider: 'range' 'min' and 'max' cannot be equal.");
  351. }
  352. parsed.spectrum = new Spectrum(entry, parsed.snap, parsed.dir, parsed.singleStep);
  353. }
  354. function testStart ( parsed, entry ) {
  355. entry = asArray(entry);
  356. // Validate input. Values aren't tested, as the public .val method
  357. // will always provide a valid location.
  358. if ( !Array.isArray( entry ) || !entry.length || entry.length > 2 ) {
  359. throw new Error("noUiSlider: 'start' option is incorrect.");
  360. }
  361. // Store the number of handles.
  362. parsed.handles = entry.length;
  363. // When the slider is initialized, the .val method will
  364. // be called with the start options.
  365. parsed.start = entry;
  366. }
  367. function testSnap ( parsed, entry ) {
  368. // Enforce 100% stepping within subranges.
  369. parsed.snap = entry;
  370. if ( typeof entry !== 'boolean' ){
  371. throw new Error("noUiSlider: 'snap' option must be a boolean.");
  372. }
  373. }
  374. function testAnimate ( parsed, entry ) {
  375. // Enforce 100% stepping within subranges.
  376. parsed.animate = entry;
  377. if ( typeof entry !== 'boolean' ){
  378. throw new Error("noUiSlider: 'animate' option must be a boolean.");
  379. }
  380. }
  381. function testAnimationDuration ( parsed, entry ) {
  382. parsed.animationDuration = entry;
  383. if ( typeof entry !== 'number' ){
  384. throw new Error("noUiSlider: 'animationDuration' option must be a number.");
  385. }
  386. }
  387. function testConnect ( parsed, entry ) {
  388. if ( entry === 'lower' && parsed.handles === 1 ) {
  389. parsed.connect = 1;
  390. } else if ( entry === 'upper' && parsed.handles === 1 ) {
  391. parsed.connect = 2;
  392. } else if ( entry === true && parsed.handles === 2 ) {
  393. parsed.connect = 3;
  394. } else if ( entry === false ) {
  395. parsed.connect = 0;
  396. } else {
  397. throw new Error("noUiSlider: 'connect' option doesn't match handle count.");
  398. }
  399. }
  400. function testOrientation ( parsed, entry ) {
  401. // Set orientation to an a numerical value for easy
  402. // array selection.
  403. switch ( entry ){
  404. case 'horizontal':
  405. parsed.ort = 0;
  406. break;
  407. case 'vertical':
  408. parsed.ort = 1;
  409. break;
  410. default:
  411. throw new Error("noUiSlider: 'orientation' option is invalid.");
  412. }
  413. }
  414. function testMargin ( parsed, entry ) {
  415. if ( !isNumeric(entry) ){
  416. throw new Error("noUiSlider: 'margin' option must be numeric.");
  417. }
  418. // Issue #582
  419. if ( entry === 0 ) {
  420. return;
  421. }
  422. parsed.margin = parsed.spectrum.getMargin(entry);
  423. if ( !parsed.margin ) {
  424. throw new Error("noUiSlider: 'margin' option is only supported on linear sliders.");
  425. }
  426. }
  427. function testLimit ( parsed, entry ) {
  428. if ( !isNumeric(entry) ){
  429. throw new Error("noUiSlider: 'limit' option must be numeric.");
  430. }
  431. parsed.limit = parsed.spectrum.getMargin(entry);
  432. if ( !parsed.limit ) {
  433. throw new Error("noUiSlider: 'limit' option is only supported on linear sliders.");
  434. }
  435. }
  436. function testDirection ( parsed, entry ) {
  437. // Set direction as a numerical value for easy parsing.
  438. // Invert connection for RTL sliders, so that the proper
  439. // handles get the connect/background classes.
  440. switch ( entry ) {
  441. case 'ltr':
  442. parsed.dir = 0;
  443. break;
  444. case 'rtl':
  445. parsed.dir = 1;
  446. parsed.connect = [0,2,1,3][parsed.connect];
  447. break;
  448. default:
  449. throw new Error("noUiSlider: 'direction' option was not recognized.");
  450. }
  451. }
  452. function testBehaviour ( parsed, entry ) {
  453. // Make sure the input is a string.
  454. if ( typeof entry !== 'string' ) {
  455. throw new Error("noUiSlider: 'behaviour' must be a string containing options.");
  456. }
  457. // Check if the string contains any keywords.
  458. // None are required.
  459. var tap = entry.indexOf('tap') >= 0,
  460. drag = entry.indexOf('drag') >= 0,
  461. fixed = entry.indexOf('fixed') >= 0,
  462. snap = entry.indexOf('snap') >= 0,
  463. hover = entry.indexOf('hover') >= 0;
  464. // Fix #472
  465. if ( drag && !parsed.connect ) {
  466. throw new Error("noUiSlider: 'drag' behaviour must be used with 'connect': true.");
  467. }
  468. parsed.events = {
  469. tap: tap || snap,
  470. drag: drag,
  471. fixed: fixed,
  472. snap: snap,
  473. hover: hover
  474. };
  475. }
  476. function testTooltips ( parsed, entry ) {
  477. var i;
  478. if ( entry === false ) {
  479. return;
  480. } else if ( entry === true ) {
  481. parsed.tooltips = [];
  482. for ( i = 0; i < parsed.handles; i++ ) {
  483. parsed.tooltips.push(true);
  484. }
  485. } else {
  486. parsed.tooltips = asArray(entry);
  487. if ( parsed.tooltips.length !== parsed.handles ) {
  488. throw new Error("noUiSlider: must pass a formatter for all handles.");
  489. }
  490. parsed.tooltips.forEach(function(formatter){
  491. if ( typeof formatter !== 'boolean' && (typeof formatter !== 'object' || typeof formatter.to !== 'function') ) {
  492. throw new Error("noUiSlider: 'tooltips' must be passed a formatter or 'false'.");
  493. }
  494. });
  495. }
  496. }
  497. function testFormat ( parsed, entry ) {
  498. parsed.format = entry;
  499. // Any object with a to and from method is supported.
  500. if ( typeof entry.to === 'function' && typeof entry.from === 'function' ) {
  501. return true;
  502. }
  503. throw new Error("noUiSlider: 'format' requires 'to' and 'from' methods.");
  504. }
  505. function testCssPrefix ( parsed, entry ) {
  506. if ( entry !== undefined && typeof entry !== 'string' && entry !== false ) {
  507. throw new Error("noUiSlider: 'cssPrefix' must be a string or `false`.");
  508. }
  509. parsed.cssPrefix = entry;
  510. }
  511. function testCssClasses ( parsed, entry ) {
  512. if ( entry !== undefined && typeof entry !== 'object' ) {
  513. throw new Error("noUiSlider: 'cssClasses' must be an object.");
  514. }
  515. if ( typeof parsed.cssPrefix === 'string' ) {
  516. parsed.cssClasses = {};
  517. for ( var key in entry ) {
  518. if ( !entry.hasOwnProperty(key) ) { continue; }
  519. parsed.cssClasses[key] = parsed.cssPrefix + entry[key];
  520. }
  521. } else {
  522. parsed.cssClasses = entry;
  523. }
  524. }
  525. // Test all developer settings and parse to assumption-safe values.
  526. function testOptions ( options ) {
  527. // To prove a fix for #537, freeze options here.
  528. // If the object is modified, an error will be thrown.
  529. // Object.freeze(options);
  530. var parsed = {
  531. margin: 0,
  532. limit: 0,
  533. animate: true,
  534. animationDuration: 300,
  535. format: defaultFormatter
  536. }, tests;
  537. // Tests are executed in the order they are presented here.
  538. tests = {
  539. 'step': { r: false, t: testStep },
  540. 'start': { r: true, t: testStart },
  541. 'connect': { r: true, t: testConnect },
  542. 'direction': { r: true, t: testDirection },
  543. 'snap': { r: false, t: testSnap },
  544. 'animate': { r: false, t: testAnimate },
  545. 'animationDuration': { r: false, t: testAnimationDuration },
  546. 'range': { r: true, t: testRange },
  547. 'orientation': { r: false, t: testOrientation },
  548. 'margin': { r: false, t: testMargin },
  549. 'limit': { r: false, t: testLimit },
  550. 'behaviour': { r: true, t: testBehaviour },
  551. 'format': { r: false, t: testFormat },
  552. 'tooltips': { r: false, t: testTooltips },
  553. 'cssPrefix': { r: false, t: testCssPrefix },
  554. 'cssClasses': { r: false, t: testCssClasses }
  555. };
  556. var defaults = {
  557. 'connect': false,
  558. 'direction': 'ltr',
  559. 'behaviour': 'tap',
  560. 'orientation': 'horizontal',
  561. 'cssPrefix' : 'noUi-',
  562. 'cssClasses': {
  563. target: 'target',
  564. base: 'base',
  565. origin: 'origin',
  566. handle: 'handle',
  567. handleLower: 'handle-lower',
  568. handleUpper: 'handle-upper',
  569. horizontal: 'horizontal',
  570. vertical: 'vertical',
  571. background: 'background',
  572. connect: 'connect',
  573. ltr: 'ltr',
  574. rtl: 'rtl',
  575. draggable: 'draggable',
  576. drag: 'state-drag',
  577. tap: 'state-tap',
  578. active: 'active',
  579. stacking: 'stacking',
  580. tooltip: 'tooltip',
  581. pips: 'pips',
  582. pipsHorizontal: 'pips-horizontal',
  583. pipsVertical: 'pips-vertical',
  584. marker: 'marker',
  585. markerHorizontal: 'marker-horizontal',
  586. markerVertical: 'marker-vertical',
  587. markerNormal: 'marker-normal',
  588. markerLarge: 'marker-large',
  589. markerSub: 'marker-sub',
  590. value: 'value',
  591. valueHorizontal: 'value-horizontal',
  592. valueVertical: 'value-vertical',
  593. valueNormal: 'value-normal',
  594. valueLarge: 'value-large',
  595. valueSub: 'value-sub'
  596. }
  597. };
  598. // Run all options through a testing mechanism to ensure correct
  599. // input. It should be noted that options might get modified to
  600. // be handled properly. E.g. wrapping integers in arrays.
  601. Object.keys(tests).forEach(function( name ){
  602. // If the option isn't set, but it is required, throw an error.
  603. if ( options[name] === undefined && defaults[name] === undefined ) {
  604. if ( tests[name].r ) {
  605. throw new Error("noUiSlider: '" + name + "' is required.");
  606. }
  607. return true;
  608. }
  609. tests[name].t( parsed, options[name] === undefined ? defaults[name] : options[name] );
  610. });
  611. // Forward pips options
  612. parsed.pips = options.pips;
  613. // Pre-define the styles.
  614. parsed.style = parsed.ort ? 'top' : 'left';
  615. return parsed;
  616. }
  617. function closure ( target, options, originalOptions ){
  618. var
  619. actions = getActions( ),
  620. // All variables local to 'closure' are prefixed with 'scope_'
  621. scope_Target = target,
  622. scope_Locations = [-1, -1],
  623. scope_Base,
  624. scope_Handles,
  625. scope_Spectrum = options.spectrum,
  626. scope_Values = [],
  627. scope_Events = {},
  628. scope_Self;
  629. // Delimit proposed values for handle positions.
  630. function getPositions ( a, b, delimit ) {
  631. // Add movement to current position.
  632. var c = a + b[0], d = a + b[1];
  633. // Only alter the other position on drag,
  634. // not on standard sliding.
  635. if ( delimit ) {
  636. if ( c < 0 ) {
  637. d += Math.abs(c);
  638. }
  639. if ( d > 100 ) {
  640. c -= ( d - 100 );
  641. }
  642. // Limit values to 0 and 100.
  643. return [limit(c), limit(d)];
  644. }
  645. return [c,d];
  646. }
  647. // Provide a clean event with standardized offset values.
  648. function fixEvent ( e, pageOffset ) {
  649. // Prevent scrolling and panning on touch events, while
  650. // attempting to slide. The tap event also depends on this.
  651. e.preventDefault();
  652. // Filter the event to register the type, which can be
  653. // touch, mouse or pointer. Offset changes need to be
  654. // made on an event specific basis.
  655. var touch = e.type.indexOf('touch') === 0,
  656. mouse = e.type.indexOf('mouse') === 0,
  657. pointer = e.type.indexOf('pointer') === 0,
  658. x,y, event = e;
  659. // IE10 implemented pointer events with a prefix;
  660. if ( e.type.indexOf('MSPointer') === 0 ) {
  661. pointer = true;
  662. }
  663. if ( touch ) {
  664. // noUiSlider supports one movement at a time,
  665. // so we can select the first 'changedTouch'.
  666. x = e.changedTouches[0].pageX;
  667. y = e.changedTouches[0].pageY;
  668. }
  669. pageOffset = pageOffset || getPageOffset();
  670. if ( mouse || pointer ) {
  671. x = e.clientX + pageOffset.x;
  672. y = e.clientY + pageOffset.y;
  673. }
  674. event.pageOffset = pageOffset;
  675. event.points = [x, y];
  676. event.cursor = mouse || pointer; // Fix #435
  677. return event;
  678. }
  679. // Append a handle to the base.
  680. function addHandle ( direction, index ) {
  681. var origin = document.createElement('div'),
  682. handle = document.createElement('div'),
  683. classModifier = [options.cssClasses.handleLower, options.cssClasses.handleUpper];
  684. if ( direction ) {
  685. classModifier.reverse();
  686. }
  687. addClass(handle, options.cssClasses.handle);
  688. addClass(handle, classModifier[index]);
  689. addClass(origin, options.cssClasses.origin);
  690. origin.appendChild(handle);
  691. return origin;
  692. }
  693. // Add the proper connection classes.
  694. function addConnection ( connect, target, handles ) {
  695. // Apply the required connection classes to the elements
  696. // that need them. Some classes are made up for several
  697. // segments listed in the class list, to allow easy
  698. // renaming and provide a minor compression benefit.
  699. switch ( connect ) {
  700. case 1: addClass(target, options.cssClasses.connect);
  701. addClass(handles[0], options.cssClasses.background);
  702. break;
  703. case 3: addClass(handles[1], options.cssClasses.background);
  704. /* falls through */
  705. case 2: addClass(handles[0], options.cssClasses.connect);
  706. /* falls through */
  707. case 0: addClass(target, options.cssClasses.background);
  708. break;
  709. }
  710. }
  711. // Add handles to the slider base.
  712. function addHandles ( nrHandles, direction, base ) {
  713. var index, handles = [];
  714. // Append handles.
  715. for ( index = 0; index < nrHandles; index += 1 ) {
  716. // Keep a list of all added handles.
  717. handles.push( base.appendChild(addHandle( direction, index )) );
  718. }
  719. return handles;
  720. }
  721. // Initialize a single slider.
  722. function addSlider ( direction, orientation, target ) {
  723. // Apply classes and data to the target.
  724. addClass(target, options.cssClasses.target);
  725. if ( direction === 0 ) {
  726. addClass(target, options.cssClasses.ltr);
  727. } else {
  728. addClass(target, options.cssClasses.rtl);
  729. }
  730. if ( orientation === 0 ) {
  731. addClass(target, options.cssClasses.horizontal);
  732. } else {
  733. addClass(target, options.cssClasses.vertical);
  734. }
  735. var div = document.createElement('div');
  736. addClass(div, options.cssClasses.base);
  737. target.appendChild(div);
  738. return div;
  739. }
  740. function addTooltip ( handle, index ) {
  741. if ( !options.tooltips[index] ) {
  742. return false;
  743. }
  744. var element = document.createElement('div');
  745. element.className = options.cssClasses.tooltip;
  746. return handle.firstChild.appendChild(element);
  747. }
  748. // The tooltips option is a shorthand for using the 'update' event.
  749. function tooltips ( ) {
  750. if ( options.dir ) {
  751. options.tooltips.reverse();
  752. }
  753. // Tooltips are added with options.tooltips in original order.
  754. var tips = scope_Handles.map(addTooltip);
  755. if ( options.dir ) {
  756. tips.reverse();
  757. options.tooltips.reverse();
  758. }
  759. bindEvent('update', function(f, o, r) {
  760. if ( tips[o] ) {
  761. tips[o].innerHTML = options.tooltips[o] === true ? f[o] : options.tooltips[o].to(r[o]);
  762. }
  763. });
  764. }
  765. function getGroup ( mode, values, stepped ) {
  766. // Use the range.
  767. if ( mode === 'range' || mode === 'steps' ) {
  768. return scope_Spectrum.xVal;
  769. }
  770. if ( mode === 'count' ) {
  771. // Divide 0 - 100 in 'count' parts.
  772. var spread = ( 100 / (values-1) ), v, i = 0;
  773. values = [];
  774. // List these parts and have them handled as 'positions'.
  775. while ((v=i++*spread) <= 100 ) {
  776. values.push(v);
  777. }
  778. mode = 'positions';
  779. }
  780. if ( mode === 'positions' ) {
  781. // Map all percentages to on-range values.
  782. return values.map(function( value ){
  783. return scope_Spectrum.fromStepping( stepped ? scope_Spectrum.getStep( value ) : value );
  784. });
  785. }
  786. if ( mode === 'values' ) {
  787. // If the value must be stepped, it needs to be converted to a percentage first.
  788. if ( stepped ) {
  789. return values.map(function( value ){
  790. // Convert to percentage, apply step, return to value.
  791. return scope_Spectrum.fromStepping( scope_Spectrum.getStep( scope_Spectrum.toStepping( value ) ) );
  792. });
  793. }
  794. // Otherwise, we can simply use the values.
  795. return values;
  796. }
  797. }
  798. function generateSpread ( density, mode, group ) {
  799. function safeIncrement(value, increment) {
  800. // Avoid floating point variance by dropping the smallest decimal places.
  801. return (value + increment).toFixed(7) / 1;
  802. }
  803. var originalSpectrumDirection = scope_Spectrum.direction,
  804. indexes = {},
  805. firstInRange = scope_Spectrum.xVal[0],
  806. lastInRange = scope_Spectrum.xVal[scope_Spectrum.xVal.length-1],
  807. ignoreFirst = false,
  808. ignoreLast = false,
  809. prevPct = 0;
  810. // This function loops the spectrum in an ltr linear fashion,
  811. // while the toStepping method is direction aware. Trick it into
  812. // believing it is ltr.
  813. scope_Spectrum.direction = 0;
  814. // Create a copy of the group, sort it and filter away all duplicates.
  815. group = unique(group.slice().sort(function(a, b){ return a - b; }));
  816. // Make sure the range starts with the first element.
  817. if ( group[0] !== firstInRange ) {
  818. group.unshift(firstInRange);
  819. ignoreFirst = true;
  820. }
  821. // Likewise for the last one.
  822. if ( group[group.length - 1] !== lastInRange ) {
  823. group.push(lastInRange);
  824. ignoreLast = true;
  825. }
  826. group.forEach(function ( current, index ) {
  827. // Get the current step and the lower + upper positions.
  828. var step, i, q,
  829. low = current,
  830. high = group[index+1],
  831. newPct, pctDifference, pctPos, type,
  832. steps, realSteps, stepsize;
  833. // When using 'steps' mode, use the provided steps.
  834. // Otherwise, we'll step on to the next subrange.
  835. if ( mode === 'steps' ) {
  836. step = scope_Spectrum.xNumSteps[ index ];
  837. }
  838. // Default to a 'full' step.
  839. if ( !step ) {
  840. step = high-low;
  841. }
  842. // Low can be 0, so test for false. If high is undefined,
  843. // we are at the last subrange. Index 0 is already handled.
  844. if ( low === false || high === undefined ) {
  845. return;
  846. }
  847. // Find all steps in the subrange.
  848. for ( i = low; i <= high; i = safeIncrement(i, step) ) {
  849. // Get the percentage value for the current step,
  850. // calculate the size for the subrange.
  851. newPct = scope_Spectrum.toStepping( i );
  852. pctDifference = newPct - prevPct;
  853. steps = pctDifference / density;
  854. realSteps = Math.round(steps);
  855. // This ratio represents the ammount of percentage-space a point indicates.
  856. // For a density 1 the points/percentage = 1. For density 2, that percentage needs to be re-devided.
  857. // Round the percentage offset to an even number, then divide by two
  858. // to spread the offset on both sides of the range.
  859. stepsize = pctDifference/realSteps;
  860. // Divide all points evenly, adding the correct number to this subrange.
  861. // Run up to <= so that 100% gets a point, event if ignoreLast is set.
  862. for ( q = 1; q <= realSteps; q += 1 ) {
  863. // The ratio between the rounded value and the actual size might be ~1% off.
  864. // Correct the percentage offset by the number of points
  865. // per subrange. density = 1 will result in 100 points on the
  866. // full range, 2 for 50, 4 for 25, etc.
  867. pctPos = prevPct + ( q * stepsize );
  868. indexes[pctPos.toFixed(5)] = ['x', 0];
  869. }
  870. // Determine the point type.
  871. type = (group.indexOf(i) > -1) ? 1 : ( mode === 'steps' ? 2 : 0 );
  872. // Enforce the 'ignoreFirst' option by overwriting the type for 0.
  873. if ( !index && ignoreFirst ) {
  874. type = 0;
  875. }
  876. if ( !(i === high && ignoreLast)) {
  877. // Mark the 'type' of this point. 0 = plain, 1 = real value, 2 = step value.
  878. indexes[newPct.toFixed(5)] = [i, type];
  879. }
  880. // Update the percentage count.
  881. prevPct = newPct;
  882. }
  883. });
  884. // Reset the spectrum.
  885. scope_Spectrum.direction = originalSpectrumDirection;
  886. return indexes;
  887. }
  888. function addMarking ( spread, filterFunc, formatter ) {
  889. var element = document.createElement('div'),
  890. out = '',
  891. valueSizeClasses = [
  892. options.cssClasses.valueNormal,
  893. options.cssClasses.valueLarge,
  894. options.cssClasses.valueSub
  895. ],
  896. markerSizeClasses = [
  897. options.cssClasses.markerNormal,
  898. options.cssClasses.markerLarge,
  899. options.cssClasses.markerSub
  900. ],
  901. valueOrientationClasses = [
  902. options.cssClasses.valueHorizontal,
  903. options.cssClasses.valueVertical
  904. ],
  905. markerOrientationClasses = [
  906. options.cssClasses.markerHorizontal,
  907. options.cssClasses.markerVertical
  908. ];
  909. addClass(element, options.cssClasses.pips);
  910. addClass(element, options.ort === 0 ? options.cssClasses.pipsHorizontal : options.cssClasses.pipsVertical);
  911. function getClasses( type, source ){
  912. var a = source === options.cssClasses.value,
  913. orientationClasses = a ? valueOrientationClasses : markerOrientationClasses,
  914. sizeClasses = a ? valueSizeClasses : markerSizeClasses;
  915. return source + ' ' + orientationClasses[options.ort] + ' ' + sizeClasses[type];
  916. }
  917. function getTags( offset, source, values ) {
  918. return 'class="' + getClasses(values[1], source) + '" style="' + options.style + ': ' + offset + '%"';
  919. }
  920. function addSpread ( offset, values ){
  921. if ( scope_Spectrum.direction ) {
  922. offset = 100 - offset;
  923. }
  924. // Apply the filter function, if it is set.
  925. values[1] = (values[1] && filterFunc) ? filterFunc(values[0], values[1]) : values[1];
  926. // Add a marker for every point
  927. out += '<div ' + getTags(offset, options.cssClasses.marker, values) + '></div>';
  928. // Values are only appended for points marked '1' or '2'.
  929. if ( values[1] ) {
  930. out += '<div ' + getTags(offset, options.cssClasses.value, values) + '>' + formatter.to(values[0]) + '</div>';
  931. }
  932. }
  933. // Append all points.
  934. Object.keys(spread).forEach(function(a){
  935. addSpread(a, spread[a]);
  936. });
  937. element.innerHTML = out;
  938. return element;
  939. }
  940. function pips ( grid ) {
  941. var mode = grid.mode,
  942. density = grid.density || 1,
  943. filter = grid.filter || false,
  944. values = grid.values || false,
  945. stepped = grid.stepped || false,
  946. group = getGroup( mode, values, stepped ),
  947. spread = generateSpread( density, mode, group ),
  948. format = grid.format || {
  949. to: Math.round
  950. };
  951. return scope_Target.appendChild(addMarking(
  952. spread,
  953. filter,
  954. format
  955. ));
  956. }
  957. // Shorthand for base dimensions.
  958. function baseSize ( ) {
  959. var rect = scope_Base.getBoundingClientRect(), alt = 'offset' + ['Width', 'Height'][options.ort];
  960. return options.ort === 0 ? (rect.width||scope_Base[alt]) : (rect.height||scope_Base[alt]);
  961. }
  962. // External event handling
  963. function fireEvent ( event, handleNumber, tap ) {
  964. var i;
  965. // During initialization, do not fire events.
  966. for ( i = 0; i < options.handles; i++ ) {
  967. if ( scope_Locations[i] === -1 ) {
  968. return;
  969. }
  970. }
  971. if ( handleNumber !== undefined && options.handles !== 1 ) {
  972. handleNumber = Math.abs(handleNumber - options.dir);
  973. }
  974. Object.keys(scope_Events).forEach(function( targetEvent ) {
  975. var eventType = targetEvent.split('.')[0];
  976. if ( event === eventType ) {
  977. scope_Events[targetEvent].forEach(function( callback ) {
  978. callback.call(
  979. // Use the slider public API as the scope ('this')
  980. scope_Self,
  981. // Return values as array, so arg_1[arg_2] is always valid.
  982. asArray(valueGet()),
  983. // Handle index, 0 or 1
  984. handleNumber,
  985. // Unformatted slider values
  986. asArray(inSliderOrder(Array.prototype.slice.call(scope_Values))),
  987. // Event is fired by tap, true or false
  988. tap || false,
  989. // Left offset of the handle, in relation to the slider
  990. scope_Locations
  991. );
  992. });
  993. }
  994. });
  995. }
  996. // Returns the input array, respecting the slider direction configuration.
  997. function inSliderOrder ( values ) {
  998. // If only one handle is used, return a single value.
  999. if ( values.length === 1 ){
  1000. return values[0];
  1001. }
  1002. if ( options.dir ) {
  1003. return values.reverse();
  1004. }
  1005. return values;
  1006. }
  1007. // Handler for attaching events trough a proxy.
  1008. function attach ( events, element, callback, data ) {
  1009. // This function can be used to 'filter' events to the slider.
  1010. // element is a node, not a nodeList
  1011. var method = function ( e ){
  1012. if ( scope_Target.hasAttribute('disabled') ) {
  1013. return false;
  1014. }
  1015. // Stop if an active 'tap' transition is taking place.
  1016. if ( hasClass(scope_Target, options.cssClasses.tap) ) {
  1017. return false;
  1018. }
  1019. e = fixEvent(e, data.pageOffset);
  1020. // Ignore right or middle clicks on start #454
  1021. if ( events === actions.start && e.buttons !== undefined && e.buttons > 1 ) {
  1022. return false;
  1023. }
  1024. // Ignore right or middle clicks on start #454
  1025. if ( data.hover && e.buttons ) {
  1026. return false;
  1027. }
  1028. e.calcPoint = e.points[ options.ort ];
  1029. // Call the event handler with the event [ and additional data ].
  1030. callback ( e, data );
  1031. }, methods = [];
  1032. // Bind a closure on the target for every event type.
  1033. events.split(' ').forEach(function( eventName ){
  1034. element.addEventListener(eventName, method, false);
  1035. methods.push([eventName, method]);
  1036. });
  1037. return methods;
  1038. }
  1039. // Handle movement on document for handle and range drag.
  1040. function move ( event, data ) {
  1041. // Fix #498
  1042. // Check value of .buttons in 'start' to work around a bug in IE10 mobile (data.buttonsProperty).
  1043. // https://connect.microsoft.com/IE/feedback/details/927005/mobile-ie10-windows-phone-buttons-property-of-pointermove-event-always-zero
  1044. // IE9 has .buttons and .which zero on mousemove.
  1045. // Firefox breaks the spec MDN defines.
  1046. if ( navigator.appVersion.indexOf("MSIE 9") === -1 && event.buttons === 0 && data.buttonsProperty !== 0 ) {
  1047. return end(event, data);
  1048. }
  1049. var handles = data.handles || scope_Handles, positions, state = false,
  1050. proposal = ((event.calcPoint - data.start) * 100) / data.baseSize,
  1051. handleNumber = handles[0] === scope_Handles[0] ? 0 : 1, i;
  1052. // Calculate relative positions for the handles.
  1053. positions = getPositions( proposal, data.positions, handles.length > 1);
  1054. state = setHandle ( handles[0], positions[handleNumber], handles.length === 1 );
  1055. if ( handles.length > 1 ) {
  1056. state = setHandle ( handles[1], positions[handleNumber?0:1], false ) || state;
  1057. if ( state ) {
  1058. // fire for both handles
  1059. for ( i = 0; i < data.handles.length; i++ ) {
  1060. fireEvent('slide', i);
  1061. }
  1062. }
  1063. } else if ( state ) {
  1064. // Fire for a single handle
  1065. fireEvent('slide', handleNumber);
  1066. }
  1067. }
  1068. // Unbind move events on document, call callbacks.
  1069. function end ( event, data ) {
  1070. // The handle is no longer active, so remove the class.
  1071. var active = scope_Base.querySelector( '.' + options.cssClasses.active ),
  1072. handleNumber = data.handles[0] === scope_Handles[0] ? 0 : 1;
  1073. if ( active !== null ) {
  1074. removeClass(active, options.cssClasses.active);
  1075. }
  1076. // Remove cursor styles and text-selection events bound to the body.
  1077. if ( event.cursor ) {
  1078. document.body.style.cursor = '';
  1079. document.body.removeEventListener('selectstart', document.body.noUiListener);
  1080. }
  1081. var d = document.documentElement;
  1082. // Unbind the move and end events, which are added on 'start'.
  1083. d.noUiListeners.forEach(function( c ) {
  1084. d.removeEventListener(c[0], c[1]);
  1085. });
  1086. // Remove dragging class.
  1087. removeClass(scope_Target, options.cssClasses.drag);
  1088. // Fire the change and set events.
  1089. fireEvent('set', handleNumber);
  1090. fireEvent('change', handleNumber);
  1091. // If this is a standard handle movement, fire the end event.
  1092. if ( data.handleNumber !== undefined ) {
  1093. fireEvent('end', data.handleNumber);
  1094. }
  1095. }
  1096. // Fire 'end' when a mouse or pen leaves the document.
  1097. function documentLeave ( event, data ) {
  1098. if ( event.type === "mouseout" && event.target.nodeName === "HTML" && event.relatedTarget === null ){
  1099. end ( event, data );
  1100. }
  1101. }
  1102. // Bind move events on document.
  1103. function start ( event, data ) {
  1104. var d = document.documentElement;
  1105. // Mark the handle as 'active' so it can be styled.
  1106. if ( data.handles.length === 1 ) {
  1107. // Support 'disabled' handles
  1108. if ( data.handles[0].hasAttribute('disabled') ) {
  1109. return false;
  1110. }
  1111. addClass(data.handles[0].children[0], options.cssClasses.active);
  1112. }
  1113. // Fix #551, where a handle gets selected instead of dragged.
  1114. event.preventDefault();
  1115. // A drag should never propagate up to the 'tap' event.
  1116. event.stopPropagation();
  1117. // Attach the move and end events.
  1118. var moveEvent = attach(actions.move, d, move, {
  1119. start: event.calcPoint,
  1120. baseSize: baseSize(),
  1121. pageOffset: event.pageOffset,
  1122. handles: data.handles,
  1123. handleNumber: data.handleNumber,
  1124. buttonsProperty: event.buttons,
  1125. positions: [
  1126. scope_Locations[0],
  1127. scope_Locations[scope_Handles.length - 1]
  1128. ]
  1129. }), endEvent = attach(actions.end, d, end, {
  1130. handles: data.handles,
  1131. handleNumber: data.handleNumber
  1132. });
  1133. var outEvent = attach("mouseout", d, documentLeave, {
  1134. handles: data.handles,
  1135. handleNumber: data.handleNumber
  1136. });
  1137. d.noUiListeners = moveEvent.concat(endEvent, outEvent);
  1138. // Text selection isn't an issue on touch devices,
  1139. // so adding cursor styles can be skipped.
  1140. if ( event.cursor ) {
  1141. // Prevent the 'I' cursor and extend the range-drag cursor.
  1142. document.body.style.cursor = getComputedStyle(event.target).cursor;
  1143. // Mark the target with a dragging state.
  1144. if ( scope_Handles.length > 1 ) {
  1145. addClass(scope_Target, options.cssClasses.drag);
  1146. }
  1147. var f = function(){
  1148. return false;
  1149. };
  1150. document.body.noUiListener = f;
  1151. // Prevent text selection when dragging the handles.
  1152. document.body.addEventListener('selectstart', f, false);
  1153. }
  1154. if ( data.handleNumber !== undefined ) {
  1155. fireEvent('start', data.handleNumber);
  1156. }
  1157. }
  1158. // Move closest handle to tapped location.
  1159. function tap ( event ) {
  1160. var location = event.calcPoint, total = 0, handleNumber, to;
  1161. // The tap event shouldn't propagate up and cause 'edge' to run.
  1162. event.stopPropagation();
  1163. // Add up the handle offsets.
  1164. scope_Handles.forEach(function(a){
  1165. total += offset(a)[ options.style ];
  1166. });
  1167. // Find the handle closest to the tapped position.
  1168. handleNumber = ( location < total/2 || scope_Handles.length === 1 ) ? 0 : 1;
  1169. // Check if handler is not disablet if yes set number to the next handler
  1170. if (scope_Handles[handleNumber].hasAttribute('disabled')) {
  1171. handleNumber = handleNumber ? 0 : 1;
  1172. }
  1173. location -= offset(scope_Base)[ options.style ];
  1174. // Calculate the new position.
  1175. to = ( location * 100 ) / baseSize();
  1176. if ( !options.events.snap ) {
  1177. // Flag the slider as it is now in a transitional state.
  1178. // Transition takes a configurable amount of ms (default 300). Re-enable the slider after that.
  1179. addClassFor( scope_Target, options.cssClasses.tap, options.animationDuration );
  1180. }
  1181. // Support 'disabled' handles
  1182. if ( scope_Handles[handleNumber].hasAttribute('disabled') ) {
  1183. return false;
  1184. }
  1185. // Find the closest handle and calculate the tapped point.
  1186. // The set handle to the new position.
  1187. setHandle( scope_Handles[handleNumber], to );
  1188. fireEvent('slide', handleNumber, true);
  1189. fireEvent('set', handleNumber, true);
  1190. fireEvent('change', handleNumber, true);
  1191. if ( options.events.snap ) {
  1192. start(event, { handles: [scope_Handles[handleNumber]] });
  1193. }
  1194. }
  1195. // Fires a 'hover' event for a hovered mouse/pen position.
  1196. function hover ( event ) {
  1197. var location = event.calcPoint - offset(scope_Base)[ options.style ],
  1198. to = scope_Spectrum.getStep(( location * 100 ) / baseSize()),
  1199. value = scope_Spectrum.fromStepping( to );
  1200. Object.keys(scope_Events).forEach(function( targetEvent ) {
  1201. if ( 'hover' === targetEvent.split('.')[0] ) {
  1202. scope_Events[targetEvent].forEach(function( callback ) {
  1203. callback.call( scope_Self, value );
  1204. });
  1205. }
  1206. });
  1207. }
  1208. // Attach events to several slider parts.
  1209. function events ( behaviour ) {
  1210. // Attach the standard drag event to the handles.
  1211. if ( !behaviour.fixed ) {
  1212. scope_Handles.forEach(function( handle, index ){
  1213. // These events are only bound to the visual handle
  1214. // element, not the 'real' origin element.
  1215. attach ( actions.start, handle.children[0], start, {
  1216. handles: [ handle ],
  1217. handleNumber: index
  1218. });
  1219. });
  1220. }
  1221. // Attach the tap event to the slider base.
  1222. if ( behaviour.tap ) {
  1223. attach ( actions.start, scope_Base, tap, {
  1224. handles: scope_Handles
  1225. });
  1226. }
  1227. // Fire hover events
  1228. if ( behaviour.hover ) {
  1229. attach ( actions.move, scope_Base, hover, { hover: true } );
  1230. }
  1231. // Make the range draggable.
  1232. if ( behaviour.drag ){
  1233. var drag = [scope_Base.querySelector( '.' + options.cssClasses.connect )];
  1234. addClass(drag[0], options.cssClasses.draggable);
  1235. // When the range is fixed, the entire range can
  1236. // be dragged by the handles. The handle in the first
  1237. // origin will propagate the start event upward,
  1238. // but it needs to be bound manually on the other.
  1239. if ( behaviour.fixed ) {
  1240. drag.push(scope_Handles[(drag[0] === scope_Handles[0] ? 1 : 0)].children[0]);
  1241. }
  1242. drag.forEach(function( element ) {
  1243. attach ( actions.start, element, start, {
  1244. handles: scope_Handles
  1245. });
  1246. });
  1247. }
  1248. }
  1249. // Test suggested values and apply margin, step.
  1250. function setHandle ( handle, to, noLimitOption ) {
  1251. var trigger = handle !== scope_Handles[0] ? 1 : 0,
  1252. lowerMargin = scope_Locations[0] + options.margin,
  1253. upperMargin = scope_Locations[1] - options.margin,
  1254. lowerLimit = scope_Locations[0] + options.limit,
  1255. upperLimit = scope_Locations[1] - options.limit;
  1256. // For sliders with multiple handles,
  1257. // limit movement to the other handle.
  1258. // Apply the margin option by adding it to the handle positions.
  1259. if ( scope_Handles.length > 1 ) {
  1260. to = trigger ? Math.max( to, lowerMargin ) : Math.min( to, upperMargin );
  1261. }
  1262. // The limit option has the opposite effect, limiting handles to a
  1263. // maximum distance from another. Limit must be > 0, as otherwise
  1264. // handles would be unmoveable. 'noLimitOption' is set to 'false'
  1265. // for the .val() method, except for pass 4/4.
  1266. if ( noLimitOption !== false && options.limit && scope_Handles.length > 1 ) {
  1267. to = trigger ? Math.min ( to, lowerLimit ) : Math.max( to, upperLimit );
  1268. }
  1269. // Handle the step option.
  1270. to = scope_Spectrum.getStep( to );
  1271. // Limit percentage to the 0 - 100 range
  1272. to = limit(to);
  1273. // Return false if handle can't move
  1274. if ( to === scope_Locations[trigger] ) {
  1275. return false;
  1276. }
  1277. // Set the handle to the new position.
  1278. // Use requestAnimationFrame for efficient painting.
  1279. // No significant effect in Chrome, Edge sees dramatic
  1280. // performace improvements.
  1281. if ( window.requestAnimationFrame ) {
  1282. window.requestAnimationFrame(function(){
  1283. handle.style[options.style] = to + '%';
  1284. });
  1285. } else {
  1286. handle.style[options.style] = to + '%';
  1287. }
  1288. // Force proper handle stacking
  1289. if ( !handle.previousSibling ) {
  1290. removeClass(handle, options.cssClasses.stacking);
  1291. if ( to > 50 ) {
  1292. addClass(handle, options.cssClasses.stacking);
  1293. }
  1294. }
  1295. // Update locations.
  1296. scope_Locations[trigger] = to;
  1297. // Convert the value to the slider stepping/range.
  1298. scope_Values[trigger] = scope_Spectrum.fromStepping( to );
  1299. fireEvent('update', trigger);
  1300. return true;
  1301. }
  1302. // Loop values from value method and apply them.
  1303. function setValues ( count, values ) {
  1304. var i, trigger, to;
  1305. // With the limit option, we'll need another limiting pass.
  1306. if ( options.limit ) {
  1307. count += 1;
  1308. }
  1309. // If there are multiple handles to be set run the setting
  1310. // mechanism twice for the first handle, to make sure it
  1311. // can be bounced of the second one properly.
  1312. for ( i = 0; i < count; i += 1 ) {
  1313. trigger = i%2;
  1314. // Get the current argument from the array.
  1315. to = values[trigger];
  1316. // Setting with null indicates an 'ignore'.
  1317. // Inputting 'false' is invalid.
  1318. if ( to !== null && to !== false ) {
  1319. // If a formatted number was passed, attemt to decode it.
  1320. if ( typeof to === 'number' ) {
  1321. to = String(to);
  1322. }
  1323. to = options.format.from( to );
  1324. // Request an update for all links if the value was invalid.
  1325. // Do so too if setting the handle fails.
  1326. if ( to === false || isNaN(to) || setHandle( scope_Handles[trigger], scope_Spectrum.toStepping( to ), i === (3 - options.dir) ) === false ) {
  1327. fireEvent('update', trigger);
  1328. }
  1329. }
  1330. }
  1331. }
  1332. // Set the slider value.
  1333. function valueSet ( input, fireSetEvent ) {
  1334. var count, values = asArray( input ), i;
  1335. // Event fires by default
  1336. fireSetEvent = (fireSetEvent === undefined ? true : !!fireSetEvent);
  1337. // The RTL settings is implemented by reversing the front-end,
  1338. // internal mechanisms are the same.
  1339. if ( options.dir && options.handles > 1 ) {
  1340. values.reverse();
  1341. }
  1342. // Animation is optional.
  1343. // Make sure the initial values where set before using animated placement.
  1344. if ( options.animate && scope_Locations[0] !== -1 ) {
  1345. addClassFor( scope_Target, options.cssClasses.tap, options.animationDuration );
  1346. }
  1347. // Determine how often to set the handles.
  1348. count = scope_Handles.length > 1 ? 3 : 1;
  1349. if ( values.length === 1 ) {
  1350. count = 1;
  1351. }
  1352. setValues ( count, values );
  1353. // Fire the 'set' event for both handles.
  1354. for ( i = 0; i < scope_Handles.length; i++ ) {
  1355. // Fire the event only for handles that received a new value, as per #579
  1356. if ( values[i] !== null && fireSetEvent ) {
  1357. fireEvent('set', i);
  1358. }
  1359. }
  1360. }
  1361. // Get the slider value.
  1362. function valueGet ( ) {
  1363. var i, retour = [];
  1364. // Get the value from all handles.
  1365. for ( i = 0; i < options.handles; i += 1 ){
  1366. retour[i] = options.format.to( scope_Values[i] );
  1367. }
  1368. return inSliderOrder( retour );
  1369. }
  1370. // Removes classes from the root and empties it.
  1371. function destroy ( ) {
  1372. for ( var key in options.cssClasses ) {
  1373. if ( !options.cssClasses.hasOwnProperty(key) ) { continue; }
  1374. removeClass(scope_Target, options.cssClasses[key]);
  1375. }
  1376. while (scope_Target.firstChild) {
  1377. scope_Target.removeChild(scope_Target.firstChild);
  1378. }
  1379. delete scope_Target.noUiSlider;
  1380. }
  1381. // Get the current step size for the slider.
  1382. function getCurrentStep ( ) {
  1383. // Check all locations, map them to their stepping point.
  1384. // Get the step point, then find it in the input list.
  1385. var retour = scope_Locations.map(function( location, index ){
  1386. var step = scope_Spectrum.getApplicableStep( location ),
  1387. // As per #391, the comparison for the decrement step can have some rounding issues.
  1388. // Round the value to the precision used in the step.
  1389. stepDecimals = countDecimals(String(step[2])),
  1390. // Get the current numeric value
  1391. value = scope_Values[index],
  1392. // To move the slider 'one step up', the current step value needs to be added.
  1393. // Use null if we are at the maximum slider value.
  1394. increment = location === 100 ? null : step[2],
  1395. // Going 'one step down' might put the slider in a different sub-range, so we
  1396. // need to switch between the current or the previous step.
  1397. prev = Number((value - step[2]).toFixed(stepDecimals)),
  1398. // If the value fits the step, return the current step value. Otherwise, use the
  1399. // previous step. Return null if the slider is at its minimum value.
  1400. decrement = location === 0 ? null : (prev >= step[1]) ? step[2] : (step[0] || false);
  1401. return [decrement, increment];
  1402. });
  1403. // Return values in the proper order.
  1404. return inSliderOrder( retour );
  1405. }
  1406. // Attach an event to this slider, possibly including a namespace
  1407. function bindEvent ( namespacedEvent, callback ) {
  1408. scope_Events[namespacedEvent] = scope_Events[namespacedEvent] || [];
  1409. scope_Events[namespacedEvent].push(callback);
  1410. // If the event bound is 'update,' fire it immediately for all handles.
  1411. if ( namespacedEvent.split('.')[0] === 'update' ) {
  1412. scope_Handles.forEach(function(a, index){
  1413. fireEvent('update', index);
  1414. });
  1415. }
  1416. }
  1417. // Undo attachment of event
  1418. function removeEvent ( namespacedEvent ) {
  1419. var event = namespacedEvent && namespacedEvent.split('.')[0],
  1420. namespace = event && namespacedEvent.substring(event.length);
  1421. Object.keys(scope_Events).forEach(function( bind ){
  1422. var tEvent = bind.split('.')[0],
  1423. tNamespace = bind.substring(tEvent.length);
  1424. if ( (!event || event === tEvent) && (!namespace || namespace === tNamespace) ) {
  1425. delete scope_Events[bind];
  1426. }
  1427. });
  1428. }
  1429. // Updateable: margin, limit, step, range, animate, snap
  1430. function updateOptions ( optionsToUpdate, fireSetEvent ) {
  1431. // Spectrum is created using the range, snap, direction and step options.
  1432. // 'snap' and 'step' can be updated, 'direction' cannot, due to event binding.
  1433. // If 'snap' and 'step' are not passed, they should remain unchanged.
  1434. var v = valueGet(), newOptions = testOptions({
  1435. start: [0, 0],
  1436. margin: optionsToUpdate.margin,
  1437. limit: optionsToUpdate.limit,
  1438. step: optionsToUpdate.step === undefined ? options.singleStep : optionsToUpdate.step,
  1439. range: optionsToUpdate.range,
  1440. animate: optionsToUpdate.animate,
  1441. snap: optionsToUpdate.snap === undefined ? options.snap : optionsToUpdate.snap
  1442. });
  1443. ['margin', 'limit', 'range', 'animate'].forEach(function(name){
  1444. // Only change options that we're actually passed to update.
  1445. if ( optionsToUpdate[name] !== undefined ) {
  1446. options[name] = optionsToUpdate[name];
  1447. }
  1448. });
  1449. // Save current spectrum direction as testOptions in testRange call
  1450. // doesn't rely on current direction
  1451. newOptions.spectrum.direction = scope_Spectrum.direction;
  1452. scope_Spectrum = newOptions.spectrum;
  1453. // Invalidate the current positioning so valueSet forces an update.
  1454. scope_Locations = [-1, -1];
  1455. valueSet(optionsToUpdate.start || v, fireSetEvent);
  1456. }
  1457. // Throw an error if the slider was already initialized.
  1458. if ( scope_Target.noUiSlider ) {
  1459. throw new Error('Slider was already initialized.');
  1460. }
  1461. // Create the base element, initialise HTML and set classes.
  1462. // Add handles and links.
  1463. scope_Base = addSlider( options.dir, options.ort, scope_Target );
  1464. scope_Handles = addHandles( options.handles, options.dir, scope_Base );
  1465. // Set the connect classes.
  1466. addConnection ( options.connect, scope_Target, scope_Handles );
  1467. if ( options.pips ) {
  1468. pips(options.pips);
  1469. }
  1470. if ( options.tooltips ) {
  1471. tooltips();
  1472. }
  1473. scope_Self = {
  1474. destroy: destroy,
  1475. steps: getCurrentStep,
  1476. on: bindEvent,
  1477. off: removeEvent,
  1478. get: valueGet,
  1479. set: valueSet,
  1480. updateOptions: updateOptions,
  1481. options: originalOptions, // Issue #600
  1482. target: scope_Target, // Issue #597
  1483. pips: pips // Issue #594
  1484. };
  1485. // Attach user events.
  1486. events( options.events );
  1487. return scope_Self;
  1488. }
  1489. // Run the standard initializer
  1490. function initialize ( target, originalOptions ) {
  1491. if ( !target.nodeName ) {
  1492. throw new Error('noUiSlider.create requires a single element.');
  1493. }
  1494. // Test the options and create the slider environment;
  1495. var options = testOptions( originalOptions, target ),
  1496. slider = closure( target, options, originalOptions );
  1497. // Use the public value method to set the start values.
  1498. slider.set(options.start);
  1499. target.noUiSlider = slider;
  1500. return slider;
  1501. }
  1502. // Use an object instead of a function for future expansibility;
  1503. return {
  1504. create: initialize
  1505. };
  1506. }));