bootstrap-slider.js 50 KB

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