bootstrap-slider.js 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. /*! =======================================================
  2. VERSION 7.1.1
  3. ========================================================= */
  4. "use strict";
  5. function _typeof(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }
  6. /*! =========================================================
  7. * bootstrap-slider.js
  8. *
  9. * Maintainers:
  10. * Kyle Kemp
  11. * - Twitter: @seiyria
  12. * - Github: seiyria
  13. * Rohit Kalkur
  14. * - Twitter: @Rovolutionary
  15. * - Github: rovolution
  16. *
  17. * =========================================================
  18. *
  19. * Licensed under the Apache License, Version 2.0 (the "License");
  20. * you may not use this file except in compliance with the License.
  21. * You may obtain a copy of the License at
  22. *
  23. * http://www.apache.org/licenses/LICENSE-2.0
  24. *
  25. * Unless required by applicable law or agreed to in writing, software
  26. * distributed under the License is distributed on an "AS IS" BASIS,
  27. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  28. * See the License for the specific language governing permissions and
  29. * limitations under the License.
  30. * ========================================================= */
  31. /**
  32. * Bridget makes jQuery widgets
  33. * v1.0.1
  34. * MIT license
  35. */
  36. (function (factory) {
  37. if (typeof define === "function" && define.amd) {
  38. try {
  39. define(["jquery"], factory);
  40. } catch (err) {
  41. define([], factory);
  42. }
  43. } else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && module.exports) {
  44. var jQuery;
  45. try {
  46. jQuery = require("jquery");
  47. } catch (err) {
  48. jQuery = null;
  49. }
  50. module.exports = factory(jQuery);
  51. } else if (window) {
  52. window.Slider = factory(window.jQuery);
  53. }
  54. })(function ($) {
  55. // Reference to Slider constructor
  56. var Slider;
  57. (function ($) {
  58. 'use strict';
  59. // -------------------------- utils -------------------------- //
  60. var slice = Array.prototype.slice;
  61. function noop() {}
  62. // -------------------------- definition -------------------------- //
  63. function defineBridget($) {
  64. // bail if no jQuery
  65. if (!$) {
  66. return;
  67. }
  68. // -------------------------- addOptionMethod -------------------------- //
  69. /**
  70. * adds option method -> $().plugin('option', {...})
  71. * @param {Function} PluginClass - constructor class
  72. */
  73. function addOptionMethod(PluginClass) {
  74. // don't overwrite original option method
  75. if (PluginClass.prototype.option) {
  76. return;
  77. }
  78. // option setter
  79. PluginClass.prototype.option = function (opts) {
  80. // bail out if not an object
  81. if (!$.isPlainObject(opts)) {
  82. return;
  83. }
  84. this.options = $.extend(true, this.options, opts);
  85. };
  86. }
  87. // -------------------------- plugin bridge -------------------------- //
  88. // helper function for logging errors
  89. // $.error breaks jQuery chaining
  90. var logError = typeof console === 'undefined' ? noop : function (message) {
  91. console.error(message);
  92. };
  93. /**
  94. * jQuery plugin bridge, access methods like $elem.plugin('method')
  95. * @param {String} namespace - plugin name
  96. * @param {Function} PluginClass - constructor class
  97. */
  98. function bridge(namespace, PluginClass) {
  99. // add to jQuery fn namespace
  100. $.fn[namespace] = function (options) {
  101. if (typeof options === 'string') {
  102. // call plugin method when first argument is a string
  103. // get arguments for method
  104. var args = slice.call(arguments, 1);
  105. for (var i = 0, len = this.length; i < len; i++) {
  106. var elem = this[i];
  107. var instance = $.data(elem, namespace);
  108. if (!instance) {
  109. logError("cannot call methods on " + namespace + " prior to initialization; " + "attempted to call '" + options + "'");
  110. continue;
  111. }
  112. if (!$.isFunction(instance[options]) || options.charAt(0) === '_') {
  113. logError("no such method '" + options + "' for " + namespace + " instance");
  114. continue;
  115. }
  116. // trigger method with arguments
  117. var returnValue = instance[options].apply(instance, args);
  118. // break look and return first value if provided
  119. if (returnValue !== undefined && returnValue !== instance) {
  120. return returnValue;
  121. }
  122. }
  123. // return this if no return value
  124. return this;
  125. } else {
  126. var objects = this.map(function () {
  127. var instance = $.data(this, namespace);
  128. if (instance) {
  129. // apply options & init
  130. instance.option(options);
  131. instance._init();
  132. } else {
  133. // initialize new instance
  134. instance = new PluginClass(this, options);
  135. $.data(this, namespace, instance);
  136. }
  137. return $(this);
  138. });
  139. if (!objects || objects.length > 1) {
  140. return objects;
  141. } else {
  142. return objects[0];
  143. }
  144. }
  145. };
  146. }
  147. // -------------------------- bridget -------------------------- //
  148. /**
  149. * converts a Prototypical class into a proper jQuery plugin
  150. * the class must have a ._init method
  151. * @param {String} namespace - plugin name, used in $().pluginName
  152. * @param {Function} PluginClass - constructor class
  153. */
  154. $.bridget = function (namespace, PluginClass) {
  155. addOptionMethod(PluginClass);
  156. bridge(namespace, PluginClass);
  157. };
  158. return $.bridget;
  159. }
  160. // get jquery from browser global
  161. defineBridget($);
  162. })($);
  163. /*************************************************
  164. BOOTSTRAP-SLIDER SOURCE CODE
  165. **************************************************/
  166. (function ($) {
  167. var ErrorMsgs = {
  168. formatInvalidInputErrorMsg: function formatInvalidInputErrorMsg(input) {
  169. return "Invalid input value '" + input + "' passed in";
  170. },
  171. callingContextNotSliderInstance: "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method"
  172. };
  173. var SliderScale = {
  174. linear: {
  175. toValue: function toValue(percentage) {
  176. var rawValue = percentage / 100 * (this.options.max - this.options.min);
  177. var shouldAdjustWithBase = true;
  178. if (this.options.ticks_positions.length > 0) {
  179. var minv,
  180. maxv,
  181. minp,
  182. maxp = 0;
  183. for (var i = 1; i < this.options.ticks_positions.length; i++) {
  184. if (percentage <= this.options.ticks_positions[i]) {
  185. minv = this.options.ticks[i - 1];
  186. minp = this.options.ticks_positions[i - 1];
  187. maxv = this.options.ticks[i];
  188. maxp = this.options.ticks_positions[i];
  189. break;
  190. }
  191. }
  192. var partialPercentage = (percentage - minp) / (maxp - minp);
  193. rawValue = minv + partialPercentage * (maxv - minv);
  194. shouldAdjustWithBase = false;
  195. }
  196. var adjustment = shouldAdjustWithBase ? this.options.min : 0;
  197. var value = adjustment + Math.round(rawValue / this.options.step) * this.options.step;
  198. if (value < this.options.min) {
  199. return this.options.min;
  200. } else if (value > this.options.max) {
  201. return this.options.max;
  202. } else {
  203. return value;
  204. }
  205. },
  206. toPercentage: function toPercentage(value) {
  207. if (this.options.max === this.options.min) {
  208. return 0;
  209. }
  210. if (this.options.ticks_positions.length > 0) {
  211. var minv,
  212. maxv,
  213. minp,
  214. maxp = 0;
  215. for (var i = 0; i < this.options.ticks.length; i++) {
  216. if (value <= this.options.ticks[i]) {
  217. minv = i > 0 ? this.options.ticks[i - 1] : 0;
  218. minp = i > 0 ? this.options.ticks_positions[i - 1] : 0;
  219. maxv = this.options.ticks[i];
  220. maxp = this.options.ticks_positions[i];
  221. break;
  222. }
  223. }
  224. if (i > 0) {
  225. var partialPercentage = (value - minv) / (maxv - minv);
  226. return minp + partialPercentage * (maxp - minp);
  227. }
  228. }
  229. return 100 * (value - this.options.min) / (this.options.max - this.options.min);
  230. }
  231. },
  232. logarithmic: {
  233. /* Based on http://stackoverflow.com/questions/846221/logarithmic-slider */
  234. toValue: function toValue(percentage) {
  235. var min = this.options.min === 0 ? 0 : Math.log(this.options.min);
  236. var max = Math.log(this.options.max);
  237. var value = Math.exp(min + (max - min) * percentage / 100);
  238. value = this.options.min + Math.round((value - this.options.min) / this.options.step) * this.options.step;
  239. /* Rounding to the nearest step could exceed the min or
  240. * max, so clip to those values. */
  241. if (value < this.options.min) {
  242. return this.options.min;
  243. } else if (value > this.options.max) {
  244. return this.options.max;
  245. } else {
  246. return value;
  247. }
  248. },
  249. toPercentage: function toPercentage(value) {
  250. if (this.options.max === this.options.min) {
  251. return 0;
  252. } else {
  253. var max = Math.log(this.options.max);
  254. var min = this.options.min === 0 ? 0 : Math.log(this.options.min);
  255. var v = value === 0 ? 0 : Math.log(value);
  256. return 100 * (v - min) / (max - min);
  257. }
  258. }
  259. }
  260. };
  261. /*************************************************
  262. CONSTRUCTOR
  263. **************************************************/
  264. Slider = function (element, options) {
  265. createNewSlider.call(this, element, options);
  266. return this;
  267. };
  268. function createNewSlider(element, options) {
  269. /*
  270. The internal state object is used to store data about the current 'state' of slider.
  271. This includes values such as the `value`, `enabled`, etc...
  272. */
  273. this._state = {
  274. value: null,
  275. enabled: null,
  276. offset: null,
  277. size: null,
  278. percentage: null,
  279. inDrag: false,
  280. over: false
  281. };
  282. if (typeof element === "string") {
  283. this.element = document.querySelector(element);
  284. } else if (element instanceof HTMLElement) {
  285. this.element = element;
  286. }
  287. /*************************************************
  288. Process Options
  289. **************************************************/
  290. options = options ? options : {};
  291. var optionTypes = Object.keys(this.defaultOptions);
  292. for (var i = 0; i < optionTypes.length; i++) {
  293. var optName = optionTypes[i];
  294. // First check if an option was passed in via the constructor
  295. var val = options[optName];
  296. // If no data attrib, then check data atrributes
  297. val = typeof val !== 'undefined' ? val : getDataAttrib(this.element, optName);
  298. // Finally, if nothing was specified, use the defaults
  299. val = val !== null ? val : this.defaultOptions[optName];
  300. // Set all options on the instance of the Slider
  301. if (!this.options) {
  302. this.options = {};
  303. }
  304. this.options[optName] = val;
  305. }
  306. /*
  307. Validate `tooltip_position` against 'orientation`
  308. - if `tooltip_position` is incompatible with orientation, swith it to a default compatible with specified `orientation`
  309. -- default for "vertical" -> "right"
  310. -- default for "horizontal" -> "left"
  311. */
  312. if (this.options.orientation === "vertical" && (this.options.tooltip_position === "top" || this.options.tooltip_position === "bottom")) {
  313. this.options.tooltip_position = "right";
  314. } else if (this.options.orientation === "horizontal" && (this.options.tooltip_position === "left" || this.options.tooltip_position === "right")) {
  315. this.options.tooltip_position = "top";
  316. }
  317. function getDataAttrib(element, optName) {
  318. var dataName = "data-slider-" + optName.replace(/_/g, '-');
  319. var dataValString = element.getAttribute(dataName);
  320. try {
  321. return JSON.parse(dataValString);
  322. } catch (err) {
  323. return dataValString;
  324. }
  325. }
  326. /*************************************************
  327. Create Markup
  328. **************************************************/
  329. var origWidth = this.element.style.width;
  330. var updateSlider = false;
  331. var parent = this.element.parentNode;
  332. var sliderTrackSelection;
  333. var sliderTrackLow, sliderTrackHigh;
  334. var sliderMinHandle;
  335. var sliderMaxHandle;
  336. if (this.sliderElem) {
  337. updateSlider = true;
  338. } else {
  339. /* Create elements needed for slider */
  340. this.sliderElem = document.createElement("div");
  341. this.sliderElem.className = "slider";
  342. /* Create slider track elements */
  343. var sliderTrack = document.createElement("div");
  344. sliderTrack.className = "slider-track";
  345. sliderTrackLow = document.createElement("div");
  346. sliderTrackLow.className = "slider-track-low";
  347. sliderTrackSelection = document.createElement("div");
  348. sliderTrackSelection.className = "slider-selection";
  349. sliderTrackHigh = document.createElement("div");
  350. sliderTrackHigh.className = "slider-track-high";
  351. sliderMinHandle = document.createElement("div");
  352. sliderMinHandle.className = "slider-handle min-slider-handle";
  353. sliderMinHandle.setAttribute('role', 'slider');
  354. sliderMinHandle.setAttribute('aria-valuemin', this.options.min);
  355. sliderMinHandle.setAttribute('aria-valuemax', this.options.max);
  356. sliderMaxHandle = document.createElement("div");
  357. sliderMaxHandle.className = "slider-handle max-slider-handle";
  358. sliderMaxHandle.setAttribute('role', 'slider');
  359. sliderMaxHandle.setAttribute('aria-valuemin', this.options.min);
  360. sliderMaxHandle.setAttribute('aria-valuemax', this.options.max);
  361. sliderTrack.appendChild(sliderTrackLow);
  362. sliderTrack.appendChild(sliderTrackSelection);
  363. sliderTrack.appendChild(sliderTrackHigh);
  364. /* Add aria-labelledby to handle's */
  365. var isLabelledbyArray = Array.isArray(this.options.labelledby);
  366. if (isLabelledbyArray && this.options.labelledby[0]) {
  367. sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby[0]);
  368. }
  369. if (isLabelledbyArray && this.options.labelledby[1]) {
  370. sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby[1]);
  371. }
  372. if (!isLabelledbyArray && this.options.labelledby) {
  373. sliderMinHandle.setAttribute('aria-labelledby', this.options.labelledby);
  374. sliderMaxHandle.setAttribute('aria-labelledby', this.options.labelledby);
  375. }
  376. /* Create ticks */
  377. this.ticks = [];
  378. if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
  379. for (i = 0; i < this.options.ticks.length; i++) {
  380. var tick = document.createElement('div');
  381. tick.className = 'slider-tick';
  382. this.ticks.push(tick);
  383. sliderTrack.appendChild(tick);
  384. }
  385. sliderTrackSelection.className += " tick-slider-selection";
  386. }
  387. sliderTrack.appendChild(sliderMinHandle);
  388. sliderTrack.appendChild(sliderMaxHandle);
  389. this.tickLabels = [];
  390. if (Array.isArray(this.options.ticks_labels) && this.options.ticks_labels.length > 0) {
  391. this.tickLabelContainer = document.createElement('div');
  392. this.tickLabelContainer.className = 'slider-tick-label-container';
  393. for (i = 0; i < this.options.ticks_labels.length; i++) {
  394. var label = document.createElement('div');
  395. var noTickPositionsSpecified = this.options.ticks_positions.length === 0;
  396. var tickLabelsIndex = this.options.reversed && noTickPositionsSpecified ? this.options.ticks_labels.length - (i + 1) : i;
  397. label.className = 'slider-tick-label';
  398. label.innerHTML = this.options.ticks_labels[tickLabelsIndex];
  399. this.tickLabels.push(label);
  400. this.tickLabelContainer.appendChild(label);
  401. }
  402. }
  403. var createAndAppendTooltipSubElements = function createAndAppendTooltipSubElements(tooltipElem) {
  404. var arrow = document.createElement("div");
  405. arrow.className = "tooltip-arrow";
  406. var inner = document.createElement("div");
  407. inner.className = "tooltip-inner";
  408. tooltipElem.appendChild(arrow);
  409. tooltipElem.appendChild(inner);
  410. };
  411. /* Create tooltip elements */
  412. var sliderTooltip = document.createElement("div");
  413. sliderTooltip.className = "tooltip tooltip-main";
  414. sliderTooltip.setAttribute('role', 'presentation');
  415. createAndAppendTooltipSubElements(sliderTooltip);
  416. var sliderTooltipMin = document.createElement("div");
  417. sliderTooltipMin.className = "tooltip tooltip-min";
  418. sliderTooltipMin.setAttribute('role', 'presentation');
  419. createAndAppendTooltipSubElements(sliderTooltipMin);
  420. var sliderTooltipMax = document.createElement("div");
  421. sliderTooltipMax.className = "tooltip tooltip-max";
  422. sliderTooltipMax.setAttribute('role', 'presentation');
  423. createAndAppendTooltipSubElements(sliderTooltipMax);
  424. /* Append components to sliderElem */
  425. this.sliderElem.appendChild(sliderTrack);
  426. this.sliderElem.appendChild(sliderTooltip);
  427. this.sliderElem.appendChild(sliderTooltipMin);
  428. this.sliderElem.appendChild(sliderTooltipMax);
  429. if (this.tickLabelContainer) {
  430. this.sliderElem.appendChild(this.tickLabelContainer);
  431. }
  432. /* Append slider element to parent container, right before the original <input> element */
  433. parent.insertBefore(this.sliderElem, this.element);
  434. /* Hide original <input> element */
  435. this.element.style.display = "none";
  436. }
  437. /* If JQuery exists, cache JQ references */
  438. if ($) {
  439. this.$element = $(this.element);
  440. this.$sliderElem = $(this.sliderElem);
  441. }
  442. /*************************************************
  443. Setup
  444. **************************************************/
  445. this.eventToCallbackMap = {};
  446. this.sliderElem.id = this.options.id;
  447. this.touchCapable = 'ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch;
  448. this.touchX = 0;
  449. this.touchY = 0;
  450. this.tooltip = this.sliderElem.querySelector('.tooltip-main');
  451. this.tooltipInner = this.tooltip.querySelector('.tooltip-inner');
  452. this.tooltip_min = this.sliderElem.querySelector('.tooltip-min');
  453. this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner');
  454. this.tooltip_max = this.sliderElem.querySelector('.tooltip-max');
  455. this.tooltipInner_max = this.tooltip_max.querySelector('.tooltip-inner');
  456. if (SliderScale[this.options.scale]) {
  457. this.options.scale = SliderScale[this.options.scale];
  458. }
  459. if (updateSlider === true) {
  460. // Reset classes
  461. this._removeClass(this.sliderElem, 'slider-horizontal');
  462. this._removeClass(this.sliderElem, 'slider-vertical');
  463. this._removeClass(this.tooltip, 'hide');
  464. this._removeClass(this.tooltip_min, 'hide');
  465. this._removeClass(this.tooltip_max, 'hide');
  466. // Undo existing inline styles for track
  467. ["left", "top", "width", "height"].forEach(function (prop) {
  468. this._removeProperty(this.trackLow, prop);
  469. this._removeProperty(this.trackSelection, prop);
  470. this._removeProperty(this.trackHigh, prop);
  471. }, this);
  472. // Undo inline styles on handles
  473. [this.handle1, this.handle2].forEach(function (handle) {
  474. this._removeProperty(handle, 'left');
  475. this._removeProperty(handle, 'top');
  476. }, this);
  477. // Undo inline styles and classes on tooltips
  478. [this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function (tooltip) {
  479. this._removeProperty(tooltip, 'left');
  480. this._removeProperty(tooltip, 'top');
  481. this._removeProperty(tooltip, 'margin-left');
  482. this._removeProperty(tooltip, 'margin-top');
  483. this._removeClass(tooltip, 'right');
  484. this._removeClass(tooltip, 'top');
  485. }, this);
  486. }
  487. if (this.options.orientation === 'vertical') {
  488. this._addClass(this.sliderElem, 'slider-vertical');
  489. this.stylePos = 'top';
  490. this.mousePos = 'pageY';
  491. this.sizePos = 'offsetHeight';
  492. } else {
  493. this._addClass(this.sliderElem, 'slider-horizontal');
  494. this.sliderElem.style.width = origWidth;
  495. this.options.orientation = 'horizontal';
  496. this.stylePos = 'left';
  497. this.mousePos = 'pageX';
  498. this.sizePos = 'offsetWidth';
  499. }
  500. this._setTooltipPosition();
  501. /* In case ticks are specified, overwrite the min and max bounds */
  502. if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
  503. this.options.max = Math.max.apply(Math, this.options.ticks);
  504. this.options.min = Math.min.apply(Math, this.options.ticks);
  505. }
  506. if (Array.isArray(this.options.value)) {
  507. this.options.range = true;
  508. this._state.value = this.options.value;
  509. } else if (this.options.range) {
  510. // User wants a range, but value is not an array
  511. this._state.value = [this.options.value, this.options.max];
  512. } else {
  513. this._state.value = this.options.value;
  514. }
  515. this.trackLow = sliderTrackLow || this.trackLow;
  516. this.trackSelection = sliderTrackSelection || this.trackSelection;
  517. this.trackHigh = sliderTrackHigh || this.trackHigh;
  518. if (this.options.selection === 'none') {
  519. this._addClass(this.trackLow, 'hide');
  520. this._addClass(this.trackSelection, 'hide');
  521. this._addClass(this.trackHigh, 'hide');
  522. }
  523. this.handle1 = sliderMinHandle || this.handle1;
  524. this.handle2 = sliderMaxHandle || this.handle2;
  525. if (updateSlider === true) {
  526. // Reset classes
  527. this._removeClass(this.handle1, 'round triangle');
  528. this._removeClass(this.handle2, 'round triangle hide');
  529. for (i = 0; i < this.ticks.length; i++) {
  530. this._removeClass(this.ticks[i], 'round triangle hide');
  531. }
  532. }
  533. var availableHandleModifiers = ['round', 'triangle', 'custom'];
  534. var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1;
  535. if (isValidHandleType) {
  536. this._addClass(this.handle1, this.options.handle);
  537. this._addClass(this.handle2, this.options.handle);
  538. for (i = 0; i < this.ticks.length; i++) {
  539. this._addClass(this.ticks[i], this.options.handle);
  540. }
  541. }
  542. this._state.offset = this._offset(this.sliderElem);
  543. this._state.size = this.sliderElem[this.sizePos];
  544. this.setValue(this._state.value);
  545. /******************************************
  546. Bind Event Listeners
  547. ******************************************/
  548. // Bind keyboard handlers
  549. this.handle1Keydown = this._keydown.bind(this, 0);
  550. this.handle1.addEventListener("keydown", this.handle1Keydown, false);
  551. this.handle2Keydown = this._keydown.bind(this, 1);
  552. this.handle2.addEventListener("keydown", this.handle2Keydown, false);
  553. this.mousedown = this._mousedown.bind(this);
  554. this.touchstart = this._touchstart.bind(this);
  555. this.touchmove = this._touchmove.bind(this);
  556. if (this.touchCapable) {
  557. // Bind touch handlers
  558. this.sliderElem.addEventListener("touchstart", this.touchstart, false);
  559. this.sliderElem.addEventListener("touchmove", this.touchmove, false);
  560. }
  561. this.sliderElem.addEventListener("mousedown", this.mousedown, false);
  562. // Bind window handlers
  563. this.resize = this._resize.bind(this);
  564. window.addEventListener("resize", this.resize, false);
  565. // Bind tooltip-related handlers
  566. if (this.options.tooltip === 'hide') {
  567. this._addClass(this.tooltip, 'hide');
  568. this._addClass(this.tooltip_min, 'hide');
  569. this._addClass(this.tooltip_max, 'hide');
  570. } else if (this.options.tooltip === 'always') {
  571. this._showTooltip();
  572. this._alwaysShowTooltip = true;
  573. } else {
  574. this.showTooltip = this._showTooltip.bind(this);
  575. this.hideTooltip = this._hideTooltip.bind(this);
  576. this.sliderElem.addEventListener("mouseenter", this.showTooltip, false);
  577. this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false);
  578. this.handle1.addEventListener("focus", this.showTooltip, false);
  579. this.handle1.addEventListener("blur", this.hideTooltip, false);
  580. this.handle2.addEventListener("focus", this.showTooltip, false);
  581. this.handle2.addEventListener("blur", this.hideTooltip, false);
  582. }
  583. if (this.options.enabled) {
  584. this.enable();
  585. } else {
  586. this.disable();
  587. }
  588. }
  589. /*************************************************
  590. INSTANCE PROPERTIES/METHODS
  591. - Any methods bound to the prototype are considered
  592. part of the plugin's `public` interface
  593. **************************************************/
  594. Slider.prototype = {
  595. _init: function _init() {}, // NOTE: Must exist to support bridget
  596. constructor: Slider,
  597. defaultOptions: {
  598. id: "",
  599. min: 0,
  600. max: 10,
  601. step: 1,
  602. precision: 0,
  603. orientation: 'horizontal',
  604. value: 5,
  605. range: false,
  606. selection: 'before',
  607. tooltip: 'show',
  608. tooltip_split: false,
  609. handle: 'round',
  610. reversed: false,
  611. enabled: true,
  612. formatter: function formatter(val) {
  613. if (Array.isArray(val)) {
  614. return val[0] + " : " + val[1];
  615. } else {
  616. return val;
  617. }
  618. },
  619. natural_arrow_keys: false,
  620. ticks: [],
  621. ticks_positions: [],
  622. ticks_labels: [],
  623. ticks_snap_bounds: 0,
  624. scale: 'linear',
  625. focus: false,
  626. tooltip_position: null,
  627. labelledby: null
  628. },
  629. getElement: function getElement() {
  630. return this.sliderElem;
  631. },
  632. getValue: function getValue() {
  633. if (this.options.range) {
  634. return this._state.value;
  635. } else {
  636. return this._state.value[0];
  637. }
  638. },
  639. setValue: function setValue(val, triggerSlideEvent, triggerChangeEvent) {
  640. if (!val) {
  641. val = 0;
  642. }
  643. var oldValue = this.getValue();
  644. this._state.value = this._validateInputValue(val);
  645. var applyPrecision = this._applyPrecision.bind(this);
  646. if (this.options.range) {
  647. this._state.value[0] = applyPrecision(this._state.value[0]);
  648. this._state.value[1] = applyPrecision(this._state.value[1]);
  649. this._state.value[0] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[0]));
  650. this._state.value[1] = Math.max(this.options.min, Math.min(this.options.max, this._state.value[1]));
  651. } else {
  652. this._state.value = applyPrecision(this._state.value);
  653. this._state.value = [Math.max(this.options.min, Math.min(this.options.max, this._state.value))];
  654. this._addClass(this.handle2, 'hide');
  655. if (this.options.selection === 'after') {
  656. this._state.value[1] = this.options.max;
  657. } else {
  658. this._state.value[1] = this.options.min;
  659. }
  660. }
  661. if (this.options.max > this.options.min) {
  662. this._state.percentage = [this._toPercentage(this._state.value[0]), this._toPercentage(this._state.value[1]), this.options.step * 100 / (this.options.max - this.options.min)];
  663. } else {
  664. this._state.percentage = [0, 0, 100];
  665. }
  666. this._layout();
  667. var newValue = this.options.range ? this._state.value : this._state.value[0];
  668. this._setDataVal(newValue);
  669. if (triggerSlideEvent === true) {
  670. this._trigger('slide', newValue);
  671. }
  672. if (oldValue !== newValue && triggerChangeEvent === true) {
  673. this._trigger('change', {
  674. oldValue: oldValue,
  675. newValue: newValue
  676. });
  677. }
  678. return this;
  679. },
  680. destroy: function destroy() {
  681. // Remove event handlers on slider elements
  682. this._removeSliderEventHandlers();
  683. // Remove the slider from the DOM
  684. this.sliderElem.parentNode.removeChild(this.sliderElem);
  685. /* Show original <input> element */
  686. this.element.style.display = "";
  687. // Clear out custom event bindings
  688. this._cleanUpEventCallbacksMap();
  689. // Remove data values
  690. this.element.removeAttribute("data");
  691. // Remove JQuery handlers/data
  692. if ($) {
  693. this._unbindJQueryEventHandlers();
  694. this.$element.removeData('slider');
  695. }
  696. },
  697. disable: function disable() {
  698. this._state.enabled = false;
  699. this.handle1.removeAttribute("tabindex");
  700. this.handle2.removeAttribute("tabindex");
  701. this._addClass(this.sliderElem, 'slider-disabled');
  702. this._trigger('slideDisabled');
  703. return this;
  704. },
  705. enable: function enable() {
  706. this._state.enabled = true;
  707. this.handle1.setAttribute("tabindex", 0);
  708. this.handle2.setAttribute("tabindex", 0);
  709. this._removeClass(this.sliderElem, 'slider-disabled');
  710. this._trigger('slideEnabled');
  711. return this;
  712. },
  713. toggle: function toggle() {
  714. if (this._state.enabled) {
  715. this.disable();
  716. } else {
  717. this.enable();
  718. }
  719. return this;
  720. },
  721. isEnabled: function isEnabled() {
  722. return this._state.enabled;
  723. },
  724. on: function on(evt, callback) {
  725. this._bindNonQueryEventHandler(evt, callback);
  726. return this;
  727. },
  728. off: function off(evt, callback) {
  729. if ($) {
  730. this.$element.off(evt, callback);
  731. this.$sliderElem.off(evt, callback);
  732. } else {
  733. this._unbindNonQueryEventHandler(evt, callback);
  734. }
  735. },
  736. getAttribute: function getAttribute(attribute) {
  737. if (attribute) {
  738. return this.options[attribute];
  739. } else {
  740. return this.options;
  741. }
  742. },
  743. setAttribute: function setAttribute(attribute, value) {
  744. this.options[attribute] = value;
  745. return this;
  746. },
  747. refresh: function refresh() {
  748. this._removeSliderEventHandlers();
  749. createNewSlider.call(this, this.element, this.options);
  750. if ($) {
  751. // Bind new instance of slider to the element
  752. $.data(this.element, 'slider', this);
  753. }
  754. return this;
  755. },
  756. relayout: function relayout() {
  757. this._resize();
  758. this._layout();
  759. return this;
  760. },
  761. /******************************+
  762. HELPERS
  763. - Any method that is not part of the public interface.
  764. - Place it underneath this comment block and write its signature like so:
  765. _fnName : function() {...}
  766. ********************************/
  767. _removeSliderEventHandlers: function _removeSliderEventHandlers() {
  768. // Remove keydown event listeners
  769. this.handle1.removeEventListener("keydown", this.handle1Keydown, false);
  770. this.handle2.removeEventListener("keydown", this.handle2Keydown, false);
  771. if (this.showTooltip) {
  772. this.handle1.removeEventListener("focus", this.showTooltip, false);
  773. this.handle2.removeEventListener("focus", this.showTooltip, false);
  774. }
  775. if (this.hideTooltip) {
  776. this.handle1.removeEventListener("blur", this.hideTooltip, false);
  777. this.handle2.removeEventListener("blur", this.hideTooltip, false);
  778. }
  779. // Remove event listeners from sliderElem
  780. if (this.showTooltip) {
  781. this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false);
  782. }
  783. if (this.hideTooltip) {
  784. this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false);
  785. }
  786. this.sliderElem.removeEventListener("touchstart", this.touchstart, false);
  787. this.sliderElem.removeEventListener("touchmove", this.touchmove, false);
  788. this.sliderElem.removeEventListener("mousedown", this.mousedown, false);
  789. // Remove window event listener
  790. window.removeEventListener("resize", this.resize, false);
  791. },
  792. _bindNonQueryEventHandler: function _bindNonQueryEventHandler(evt, callback) {
  793. if (this.eventToCallbackMap[evt] === undefined) {
  794. this.eventToCallbackMap[evt] = [];
  795. }
  796. this.eventToCallbackMap[evt].push(callback);
  797. },
  798. _unbindNonQueryEventHandler: function _unbindNonQueryEventHandler(evt, callback) {
  799. var callbacks = this.eventToCallbackMap[evt];
  800. if (callbacks !== undefined) {
  801. for (var i = 0; i < callbacks.length; i++) {
  802. if (callbacks[i] === callback) {
  803. callbacks.splice(i, 1);
  804. break;
  805. }
  806. }
  807. }
  808. },
  809. _cleanUpEventCallbacksMap: function _cleanUpEventCallbacksMap() {
  810. var eventNames = Object.keys(this.eventToCallbackMap);
  811. for (var i = 0; i < eventNames.length; i++) {
  812. var eventName = eventNames[i];
  813. this.eventToCallbackMap[eventName] = null;
  814. }
  815. },
  816. _showTooltip: function _showTooltip() {
  817. if (this.options.tooltip_split === false) {
  818. this._addClass(this.tooltip, 'in');
  819. this.tooltip_min.style.display = 'none';
  820. this.tooltip_max.style.display = 'none';
  821. } else {
  822. this._addClass(this.tooltip_min, 'in');
  823. this._addClass(this.tooltip_max, 'in');
  824. this.tooltip.style.display = 'none';
  825. }
  826. this._state.over = true;
  827. },
  828. _hideTooltip: function _hideTooltip() {
  829. if (this._state.inDrag === false && this.alwaysShowTooltip !== true) {
  830. this._removeClass(this.tooltip, 'in');
  831. this._removeClass(this.tooltip_min, 'in');
  832. this._removeClass(this.tooltip_max, 'in');
  833. }
  834. this._state.over = false;
  835. },
  836. _layout: function _layout() {
  837. var positionPercentages;
  838. if (this.options.reversed) {
  839. positionPercentages = [100 - this._state.percentage[0], this.options.range ? 100 - this._state.percentage[1] : this._state.percentage[1]];
  840. } else {
  841. positionPercentages = [this._state.percentage[0], this._state.percentage[1]];
  842. }
  843. this.handle1.style[this.stylePos] = positionPercentages[0] + '%';
  844. this.handle1.setAttribute('aria-valuenow', this._state.value[0]);
  845. this.handle2.style[this.stylePos] = positionPercentages[1] + '%';
  846. this.handle2.setAttribute('aria-valuenow', this._state.value[1]);
  847. /* Position ticks and labels */
  848. if (Array.isArray(this.options.ticks) && this.options.ticks.length > 0) {
  849. var styleSize = this.options.orientation === 'vertical' ? 'height' : 'width';
  850. var styleMargin = this.options.orientation === 'vertical' ? 'marginTop' : 'marginLeft';
  851. var labelSize = this._state.size / (this.options.ticks.length - 1);
  852. if (this.tickLabelContainer) {
  853. var extraMargin = 0;
  854. if (this.options.ticks_positions.length === 0) {
  855. if (this.options.orientation !== 'vertical') {
  856. this.tickLabelContainer.style[styleMargin] = -labelSize / 2 + 'px';
  857. }
  858. extraMargin = this.tickLabelContainer.offsetHeight;
  859. } else {
  860. /* Chidren are position absolute, calculate height by finding the max offsetHeight of a child */
  861. for (i = 0; i < this.tickLabelContainer.childNodes.length; i++) {
  862. if (this.tickLabelContainer.childNodes[i].offsetHeight > extraMargin) {
  863. extraMargin = this.tickLabelContainer.childNodes[i].offsetHeight;
  864. }
  865. }
  866. }
  867. if (this.options.orientation === 'horizontal') {
  868. this.sliderElem.style.marginBottom = extraMargin + 'px';
  869. }
  870. }
  871. for (var i = 0; i < this.options.ticks.length; i++) {
  872. var percentage = this.options.ticks_positions[i] || this._toPercentage(this.options.ticks[i]);
  873. if (this.options.reversed) {
  874. percentage = 100 - percentage;
  875. }
  876. this.ticks[i].style[this.stylePos] = percentage + '%';
  877. /* Set class labels to denote whether ticks are in the selection */
  878. this._removeClass(this.ticks[i], 'in-selection');
  879. if (!this.options.range) {
  880. if (this.options.selection === 'after' && percentage >= positionPercentages[0]) {
  881. this._addClass(this.ticks[i], 'in-selection');
  882. } else if (this.options.selection === 'before' && percentage <= positionPercentages[0]) {
  883. this._addClass(this.ticks[i], 'in-selection');
  884. }
  885. } else if (percentage >= positionPercentages[0] && percentage <= positionPercentages[1]) {
  886. this._addClass(this.ticks[i], 'in-selection');
  887. }
  888. if (this.tickLabels[i]) {
  889. this.tickLabels[i].style[styleSize] = labelSize + 'px';
  890. if (this.options.orientation !== 'vertical' && this.options.ticks_positions[i] !== undefined) {
  891. this.tickLabels[i].style.position = 'absolute';
  892. this.tickLabels[i].style[this.stylePos] = percentage + '%';
  893. this.tickLabels[i].style[styleMargin] = -labelSize / 2 + 'px';
  894. } else if (this.options.orientation === 'vertical') {
  895. this.tickLabels[i].style['marginLeft'] = this.sliderElem.offsetWidth + 'px';
  896. this.tickLabelContainer.style['marginTop'] = this.sliderElem.offsetWidth / 2 * -1 + 'px';
  897. }
  898. }
  899. }
  900. }
  901. var formattedTooltipVal;
  902. if (this.options.range) {
  903. formattedTooltipVal = this.options.formatter(this._state.value);
  904. this._setText(this.tooltipInner, formattedTooltipVal);
  905. this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0]) / 2 + '%';
  906. if (this.options.orientation === 'vertical') {
  907. this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
  908. } else {
  909. this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
  910. }
  911. if (this.options.orientation === 'vertical') {
  912. this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
  913. } else {
  914. this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
  915. }
  916. var innerTooltipMinText = this.options.formatter(this._state.value[0]);
  917. this._setText(this.tooltipInner_min, innerTooltipMinText);
  918. var innerTooltipMaxText = this.options.formatter(this._state.value[1]);
  919. this._setText(this.tooltipInner_max, innerTooltipMaxText);
  920. this.tooltip_min.style[this.stylePos] = positionPercentages[0] + '%';
  921. if (this.options.orientation === 'vertical') {
  922. this._css(this.tooltip_min, 'margin-top', -this.tooltip_min.offsetHeight / 2 + 'px');
  923. } else {
  924. this._css(this.tooltip_min, 'margin-left', -this.tooltip_min.offsetWidth / 2 + 'px');
  925. }
  926. this.tooltip_max.style[this.stylePos] = positionPercentages[1] + '%';
  927. if (this.options.orientation === 'vertical') {
  928. this._css(this.tooltip_max, 'margin-top', -this.tooltip_max.offsetHeight / 2 + 'px');
  929. } else {
  930. this._css(this.tooltip_max, 'margin-left', -this.tooltip_max.offsetWidth / 2 + 'px');
  931. }
  932. } else {
  933. formattedTooltipVal = this.options.formatter(this._state.value[0]);
  934. this._setText(this.tooltipInner, formattedTooltipVal);
  935. this.tooltip.style[this.stylePos] = positionPercentages[0] + '%';
  936. if (this.options.orientation === 'vertical') {
  937. this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
  938. } else {
  939. this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
  940. }
  941. }
  942. if (this.options.orientation === 'vertical') {
  943. this.trackLow.style.top = '0';
  944. this.trackLow.style.height = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
  945. this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
  946. this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) + '%';
  947. this.trackHigh.style.bottom = '0';
  948. this.trackHigh.style.height = 100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1]) + '%';
  949. } else {
  950. this.trackLow.style.left = '0';
  951. this.trackLow.style.width = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
  952. this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) + '%';
  953. this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) + '%';
  954. this.trackHigh.style.right = '0';
  955. this.trackHigh.style.width = 100 - Math.min(positionPercentages[0], positionPercentages[1]) - Math.abs(positionPercentages[0] - positionPercentages[1]) + '%';
  956. var offset_min = this.tooltip_min.getBoundingClientRect();
  957. var offset_max = this.tooltip_max.getBoundingClientRect();
  958. if (this.options.tooltip_position === 'bottom') {
  959. if (offset_min.right > offset_max.left) {
  960. this._removeClass(this.tooltip_max, 'bottom');
  961. this._addClass(this.tooltip_max, 'top');
  962. this.tooltip_max.style.top = '';
  963. this.tooltip_max.style.bottom = 22 + 'px';
  964. } else {
  965. this._removeClass(this.tooltip_max, 'top');
  966. this._addClass(this.tooltip_max, 'bottom');
  967. this.tooltip_max.style.top = this.tooltip_min.style.top;
  968. this.tooltip_max.style.bottom = '';
  969. }
  970. } else {
  971. if (offset_min.right > offset_max.left) {
  972. this._removeClass(this.tooltip_max, 'top');
  973. this._addClass(this.tooltip_max, 'bottom');
  974. this.tooltip_max.style.top = 18 + 'px';
  975. } else {
  976. this._removeClass(this.tooltip_max, 'bottom');
  977. this._addClass(this.tooltip_max, 'top');
  978. this.tooltip_max.style.top = this.tooltip_min.style.top;
  979. }
  980. }
  981. }
  982. },
  983. _resize: function _resize(ev) {
  984. /*jshint unused:false*/
  985. this._state.offset = this._offset(this.sliderElem);
  986. this._state.size = this.sliderElem[this.sizePos];
  987. this._layout();
  988. },
  989. _removeProperty: function _removeProperty(element, prop) {
  990. if (element.style.removeProperty) {
  991. element.style.removeProperty(prop);
  992. } else {
  993. element.style.removeAttribute(prop);
  994. }
  995. },
  996. _mousedown: function _mousedown(ev) {
  997. if (!this._state.enabled) {
  998. return false;
  999. }
  1000. this._state.offset = this._offset(this.sliderElem);
  1001. this._state.size = this.sliderElem[this.sizePos];
  1002. var percentage = this._getPercentage(ev);
  1003. if (this.options.range) {
  1004. var diff1 = Math.abs(this._state.percentage[0] - percentage);
  1005. var diff2 = Math.abs(this._state.percentage[1] - percentage);
  1006. this._state.dragged = diff1 < diff2 ? 0 : 1;
  1007. this._adjustPercentageForRangeSliders(percentage);
  1008. } else {
  1009. this._state.dragged = 0;
  1010. }
  1011. this._state.percentage[this._state.dragged] = percentage;
  1012. this._layout();
  1013. if (this.touchCapable) {
  1014. document.removeEventListener("touchmove", this.mousemove, false);
  1015. document.removeEventListener("touchend", this.mouseup, false);
  1016. }
  1017. if (this.mousemove) {
  1018. document.removeEventListener("mousemove", this.mousemove, false);
  1019. }
  1020. if (this.mouseup) {
  1021. document.removeEventListener("mouseup", this.mouseup, false);
  1022. }
  1023. this.mousemove = this._mousemove.bind(this);
  1024. this.mouseup = this._mouseup.bind(this);
  1025. if (this.touchCapable) {
  1026. // Touch: Bind touch events:
  1027. document.addEventListener("touchmove", this.mousemove, false);
  1028. document.addEventListener("touchend", this.mouseup, false);
  1029. }
  1030. // Bind mouse events:
  1031. document.addEventListener("mousemove", this.mousemove, false);
  1032. document.addEventListener("mouseup", this.mouseup, false);
  1033. this._state.inDrag = true;
  1034. var newValue = this._calculateValue();
  1035. this._trigger('slideStart', newValue);
  1036. this._setDataVal(newValue);
  1037. this.setValue(newValue, false, true);
  1038. this._pauseEvent(ev);
  1039. if (this.options.focus) {
  1040. this._triggerFocusOnHandle(this._state.dragged);
  1041. }
  1042. return true;
  1043. },
  1044. _touchstart: function _touchstart(ev) {
  1045. if (ev.changedTouches === undefined) {
  1046. this._mousedown(ev);
  1047. return;
  1048. }
  1049. var touch = ev.changedTouches[0];
  1050. this.touchX = touch.pageX;
  1051. this.touchY = touch.pageY;
  1052. },
  1053. _triggerFocusOnHandle: function _triggerFocusOnHandle(handleIdx) {
  1054. if (handleIdx === 0) {
  1055. this.handle1.focus();
  1056. }
  1057. if (handleIdx === 1) {
  1058. this.handle2.focus();
  1059. }
  1060. },
  1061. _keydown: function _keydown(handleIdx, ev) {
  1062. if (!this._state.enabled) {
  1063. return false;
  1064. }
  1065. var dir;
  1066. switch (ev.keyCode) {
  1067. case 37: // left
  1068. case 40:
  1069. // down
  1070. dir = -1;
  1071. break;
  1072. case 39: // right
  1073. case 38:
  1074. // up
  1075. dir = 1;
  1076. break;
  1077. }
  1078. if (!dir) {
  1079. return;
  1080. }
  1081. // use natural arrow keys instead of from min to max
  1082. if (this.options.natural_arrow_keys) {
  1083. var ifVerticalAndNotReversed = this.options.orientation === 'vertical' && !this.options.reversed;
  1084. var ifHorizontalAndReversed = this.options.orientation === 'horizontal' && this.options.reversed;
  1085. if (ifVerticalAndNotReversed || ifHorizontalAndReversed) {
  1086. dir = -dir;
  1087. }
  1088. }
  1089. var val = this._state.value[handleIdx] + dir * this.options.step;
  1090. if (this.options.range) {
  1091. val = [!handleIdx ? val : this._state.value[0], handleIdx ? val : this._state.value[1]];
  1092. }
  1093. this._trigger('slideStart', val);
  1094. this._setDataVal(val);
  1095. this.setValue(val, true, true);
  1096. this._setDataVal(val);
  1097. this._trigger('slideStop', val);
  1098. this._layout();
  1099. this._pauseEvent(ev);
  1100. return false;
  1101. },
  1102. _pauseEvent: function _pauseEvent(ev) {
  1103. if (ev.stopPropagation) {
  1104. ev.stopPropagation();
  1105. }
  1106. if (ev.preventDefault) {
  1107. ev.preventDefault();
  1108. }
  1109. ev.cancelBubble = true;
  1110. ev.returnValue = false;
  1111. },
  1112. _mousemove: function _mousemove(ev) {
  1113. if (!this._state.enabled) {
  1114. return false;
  1115. }
  1116. var percentage = this._getPercentage(ev);
  1117. this._adjustPercentageForRangeSliders(percentage);
  1118. this._state.percentage[this._state.dragged] = percentage;
  1119. this._layout();
  1120. var val = this._calculateValue(true);
  1121. this.setValue(val, true, true);
  1122. return false;
  1123. },
  1124. _touchmove: function _touchmove(ev) {
  1125. if (ev.changedTouches === undefined) {
  1126. return;
  1127. }
  1128. var touch = ev.changedTouches[0];
  1129. var xDiff = touch.pageX - this.touchX;
  1130. var yDiff = touch.pageY - this.touchY;
  1131. if (!this._state.inDrag) {
  1132. // Vertical Slider
  1133. if (this.options.orientation === 'vertical' && xDiff <= 5 && xDiff >= -5 && (yDiff >= 15 || yDiff <= -15)) {
  1134. this._mousedown(ev);
  1135. }
  1136. // Horizontal slider.
  1137. else if (yDiff <= 5 && yDiff >= -5 && (xDiff >= 15 || xDiff <= -15)) {
  1138. this._mousedown(ev);
  1139. }
  1140. }
  1141. },
  1142. _adjustPercentageForRangeSliders: function _adjustPercentageForRangeSliders(percentage) {
  1143. if (this.options.range) {
  1144. var precision = this._getNumDigitsAfterDecimalPlace(percentage);
  1145. precision = precision ? precision - 1 : 0;
  1146. var percentageWithAdjustedPrecision = this._applyToFixedAndParseFloat(percentage, precision);
  1147. if (this._state.dragged === 0 && this._applyToFixedAndParseFloat(this._state.percentage[1], precision) < percentageWithAdjustedPrecision) {
  1148. this._state.percentage[0] = this._state.percentage[1];
  1149. this._state.dragged = 1;
  1150. } else if (this._state.dragged === 1 && this._applyToFixedAndParseFloat(this._state.percentage[0], precision) > percentageWithAdjustedPrecision) {
  1151. this._state.percentage[1] = this._state.percentage[0];
  1152. this._state.dragged = 0;
  1153. }
  1154. }
  1155. },
  1156. _mouseup: function _mouseup() {
  1157. if (!this._state.enabled) {
  1158. return false;
  1159. }
  1160. if (this.touchCapable) {
  1161. // Touch: Unbind touch event handlers:
  1162. document.removeEventListener("touchmove", this.mousemove, false);
  1163. document.removeEventListener("touchend", this.mouseup, false);
  1164. }
  1165. // Unbind mouse event handlers:
  1166. document.removeEventListener("mousemove", this.mousemove, false);
  1167. document.removeEventListener("mouseup", this.mouseup, false);
  1168. this._state.inDrag = false;
  1169. if (this._state.over === false) {
  1170. this._hideTooltip();
  1171. }
  1172. var val = this._calculateValue(true);
  1173. this._layout();
  1174. this._setDataVal(val);
  1175. this._trigger('slideStop', val);
  1176. return false;
  1177. },
  1178. _calculateValue: function _calculateValue(snapToClosestTick) {
  1179. var val;
  1180. if (this.options.range) {
  1181. val = [this.options.min, this.options.max];
  1182. if (this._state.percentage[0] !== 0) {
  1183. val[0] = this._toValue(this._state.percentage[0]);
  1184. val[0] = this._applyPrecision(val[0]);
  1185. }
  1186. if (this._state.percentage[1] !== 100) {
  1187. val[1] = this._toValue(this._state.percentage[1]);
  1188. val[1] = this._applyPrecision(val[1]);
  1189. }
  1190. } else {
  1191. val = this._toValue(this._state.percentage[0]);
  1192. val = parseFloat(val);
  1193. val = this._applyPrecision(val);
  1194. }
  1195. if (snapToClosestTick) {
  1196. var min = [val, Infinity];
  1197. for (var i = 0; i < this.options.ticks.length; i++) {
  1198. var diff = Math.abs(this.options.ticks[i] - val);
  1199. if (diff <= min[1]) {
  1200. min = [this.options.ticks[i], diff];
  1201. }
  1202. }
  1203. if (min[1] <= this.options.ticks_snap_bounds) {
  1204. return min[0];
  1205. }
  1206. }
  1207. return val;
  1208. },
  1209. _applyPrecision: function _applyPrecision(val) {
  1210. var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.options.step);
  1211. return this._applyToFixedAndParseFloat(val, precision);
  1212. },
  1213. _getNumDigitsAfterDecimalPlace: function _getNumDigitsAfterDecimalPlace(num) {
  1214. var match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
  1215. if (!match) {
  1216. return 0;
  1217. }
  1218. return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
  1219. },
  1220. _applyToFixedAndParseFloat: function _applyToFixedAndParseFloat(num, toFixedInput) {
  1221. var truncatedNum = num.toFixed(toFixedInput);
  1222. return parseFloat(truncatedNum);
  1223. },
  1224. /*
  1225. Credits to Mike Samuel for the following method!
  1226. Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
  1227. */
  1228. _getPercentage: function _getPercentage(ev) {
  1229. if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) {
  1230. ev = ev.touches[0];
  1231. }
  1232. var eventPosition = ev[this.mousePos];
  1233. var sliderOffset = this._state.offset[this.stylePos];
  1234. var distanceToSlide = eventPosition - sliderOffset;
  1235. // Calculate what percent of the length the slider handle has slid
  1236. var percentage = distanceToSlide / this._state.size * 100;
  1237. percentage = Math.round(percentage / this._state.percentage[2]) * this._state.percentage[2];
  1238. if (this.options.reversed) {
  1239. percentage = 100 - percentage;
  1240. }
  1241. // Make sure the percent is within the bounds of the slider.
  1242. // 0% corresponds to the 'min' value of the slide
  1243. // 100% corresponds to the 'max' value of the slide
  1244. return Math.max(0, Math.min(100, percentage));
  1245. },
  1246. _validateInputValue: function _validateInputValue(val) {
  1247. if (typeof val === 'number') {
  1248. return val;
  1249. } else if (Array.isArray(val)) {
  1250. this._validateArray(val);
  1251. return val;
  1252. } else {
  1253. throw new Error(ErrorMsgs.formatInvalidInputErrorMsg(val));
  1254. }
  1255. },
  1256. _validateArray: function _validateArray(val) {
  1257. for (var i = 0; i < val.length; i++) {
  1258. var input = val[i];
  1259. if (typeof input !== 'number') {
  1260. throw new Error(ErrorMsgs.formatInvalidInputErrorMsg(input));
  1261. }
  1262. }
  1263. },
  1264. _setDataVal: function _setDataVal(val) {
  1265. this.element.setAttribute('data-value', val);
  1266. this.element.setAttribute('value', val);
  1267. this.element.value = val;
  1268. },
  1269. _trigger: function _trigger(evt, val) {
  1270. val = val || val === 0 ? val : undefined;
  1271. var callbackFnArray = this.eventToCallbackMap[evt];
  1272. if (callbackFnArray && callbackFnArray.length) {
  1273. for (var i = 0; i < callbackFnArray.length; i++) {
  1274. var callbackFn = callbackFnArray[i];
  1275. callbackFn(val);
  1276. }
  1277. }
  1278. /* If JQuery exists, trigger JQuery events */
  1279. if ($) {
  1280. this._triggerJQueryEvent(evt, val);
  1281. }
  1282. },
  1283. _triggerJQueryEvent: function _triggerJQueryEvent(evt, val) {
  1284. var eventData = {
  1285. type: evt,
  1286. value: val
  1287. };
  1288. this.$element.trigger(eventData);
  1289. this.$sliderElem.trigger(eventData);
  1290. },
  1291. _unbindJQueryEventHandlers: function _unbindJQueryEventHandlers() {
  1292. this.$element.off();
  1293. this.$sliderElem.off();
  1294. },
  1295. _setText: function _setText(element, text) {
  1296. if (typeof element.textContent !== "undefined") {
  1297. element.textContent = text;
  1298. } else if (typeof element.innerText !== "undefined") {
  1299. element.innerText = text;
  1300. }
  1301. },
  1302. _removeClass: function _removeClass(element, classString) {
  1303. var classes = classString.split(" ");
  1304. var newClasses = element.className;
  1305. for (var i = 0; i < classes.length; i++) {
  1306. var classTag = classes[i];
  1307. var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
  1308. newClasses = newClasses.replace(regex, " ");
  1309. }
  1310. element.className = newClasses.trim();
  1311. },
  1312. _addClass: function _addClass(element, classString) {
  1313. var classes = classString.split(" ");
  1314. var newClasses = element.className;
  1315. for (var i = 0; i < classes.length; i++) {
  1316. var classTag = classes[i];
  1317. var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
  1318. var ifClassExists = regex.test(newClasses);
  1319. if (!ifClassExists) {
  1320. newClasses += " " + classTag;
  1321. }
  1322. }
  1323. element.className = newClasses.trim();
  1324. },
  1325. _offsetLeft: function _offsetLeft(obj) {
  1326. return obj.getBoundingClientRect().left;
  1327. },
  1328. _offsetTop: function _offsetTop(obj) {
  1329. var offsetTop = obj.offsetTop;
  1330. while ((obj = obj.offsetParent) && !isNaN(obj.offsetTop)) {
  1331. offsetTop += obj.offsetTop;
  1332. if (obj.tagName !== 'BODY') {
  1333. offsetTop -= obj.scrollTop;
  1334. }
  1335. }
  1336. return offsetTop;
  1337. },
  1338. _offset: function _offset(obj) {
  1339. return {
  1340. left: this._offsetLeft(obj),
  1341. top: this._offsetTop(obj)
  1342. };
  1343. },
  1344. _css: function _css(elementRef, styleName, value) {
  1345. if ($) {
  1346. $.style(elementRef, styleName, value);
  1347. } else {
  1348. var style = styleName.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function (all, letter) {
  1349. return letter.toUpperCase();
  1350. });
  1351. elementRef.style[style] = value;
  1352. }
  1353. },
  1354. _toValue: function _toValue(percentage) {
  1355. return this.options.scale.toValue.apply(this, [percentage]);
  1356. },
  1357. _toPercentage: function _toPercentage(value) {
  1358. return this.options.scale.toPercentage.apply(this, [value]);
  1359. },
  1360. _setTooltipPosition: function _setTooltipPosition() {
  1361. var tooltips = [this.tooltip, this.tooltip_min, this.tooltip_max];
  1362. if (this.options.orientation === 'vertical') {
  1363. var tooltipPos = this.options.tooltip_position || 'right';
  1364. var oppositeSide = tooltipPos === 'left' ? 'right' : 'left';
  1365. tooltips.forEach((function (tooltip) {
  1366. this._addClass(tooltip, tooltipPos);
  1367. tooltip.style[oppositeSide] = '100%';
  1368. }).bind(this));
  1369. } else if (this.options.tooltip_position === 'bottom') {
  1370. tooltips.forEach((function (tooltip) {
  1371. this._addClass(tooltip, 'bottom');
  1372. tooltip.style.top = 22 + 'px';
  1373. }).bind(this));
  1374. } else {
  1375. tooltips.forEach((function (tooltip) {
  1376. this._addClass(tooltip, 'top');
  1377. tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px';
  1378. }).bind(this));
  1379. }
  1380. }
  1381. };
  1382. /*********************************
  1383. Attach to global namespace
  1384. *********************************/
  1385. if ($) {
  1386. var namespace = $.fn.slider ? 'bootstrapSlider' : 'slider';
  1387. $.bridget(namespace, Slider);
  1388. // Auto-Register data-provide="slider" Elements
  1389. $(function () {
  1390. $("input[data-provide=slider]")[namespace]();
  1391. });
  1392. }
  1393. })($);
  1394. return Slider;
  1395. });