bootstrap-slider.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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( $ ) {
  32. ( function( $ ) {
  33. 'use strict';
  34. // -------------------------- utils -------------------------- //
  35. var slice = Array.prototype.slice;
  36. function noop() {}
  37. // -------------------------- definition -------------------------- //
  38. function defineBridget( $ ) {
  39. // bail if no jQuery
  40. if ( !$ ) {
  41. return;
  42. }
  43. // -------------------------- addOptionMethod -------------------------- //
  44. /**
  45. * adds option method -> $().plugin('option', {...})
  46. * @param {Function} PluginClass - constructor class
  47. */
  48. function addOptionMethod( PluginClass ) {
  49. // don't overwrite original option method
  50. if ( PluginClass.prototype.option ) {
  51. return;
  52. }
  53. // option setter
  54. PluginClass.prototype.option = function( opts ) {
  55. // bail out if not an object
  56. if ( !$.isPlainObject( opts ) ){
  57. return;
  58. }
  59. this.options = $.extend( true, this.options, opts );
  60. };
  61. }
  62. // -------------------------- plugin bridge -------------------------- //
  63. // helper function for logging errors
  64. // $.error breaks jQuery chaining
  65. var logError = typeof console === 'undefined' ? noop :
  66. function( message ) {
  67. console.error( message );
  68. };
  69. /**
  70. * jQuery plugin bridge, access methods like $elem.plugin('method')
  71. * @param {String} namespace - plugin name
  72. * @param {Function} PluginClass - constructor class
  73. */
  74. function bridge( namespace, PluginClass ) {
  75. // add to jQuery fn namespace
  76. $.fn[ namespace ] = function( options ) {
  77. if ( typeof options === 'string' ) {
  78. // call plugin method when first argument is a string
  79. // get arguments for method
  80. var args = slice.call( arguments, 1 );
  81. for ( var i=0, len = this.length; i < len; i++ ) {
  82. var elem = this[i];
  83. var instance = $.data( elem, namespace );
  84. if ( !instance ) {
  85. logError( "cannot call methods on " + namespace + " prior to initialization; " +
  86. "attempted to call '" + options + "'" );
  87. continue;
  88. }
  89. if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) {
  90. logError( "no such method '" + options + "' for " + namespace + " instance" );
  91. continue;
  92. }
  93. // trigger method with arguments
  94. var returnValue = instance[ options ].apply( instance, args);
  95. // break look and return first value if provided
  96. if ( returnValue !== undefined && returnValue !== instance) {
  97. return returnValue;
  98. }
  99. }
  100. // return this if no return value
  101. return this;
  102. } else {
  103. var objects = this.map( function() {
  104. var instance = $.data( this, namespace );
  105. if ( instance ) {
  106. // apply options & init
  107. instance.option( options );
  108. instance._init();
  109. } else {
  110. // initialize new instance
  111. instance = new PluginClass( this, options );
  112. $.data( this, namespace, instance );
  113. }
  114. return $(this);
  115. });
  116. if(!objects || objects.length > 1) {
  117. return objects;
  118. } else {
  119. return objects[0];
  120. }
  121. }
  122. };
  123. }
  124. // -------------------------- bridget -------------------------- //
  125. /**
  126. * converts a Prototypical class into a proper jQuery plugin
  127. * the class must have a ._init method
  128. * @param {String} namespace - plugin name, used in $().pluginName
  129. * @param {Function} PluginClass - constructor class
  130. */
  131. $.bridget = function( namespace, PluginClass ) {
  132. addOptionMethod( PluginClass );
  133. bridge( namespace, PluginClass );
  134. };
  135. return $.bridget;
  136. }
  137. // get jquery from browser global
  138. defineBridget( $ );
  139. })( $ );
  140. /*************************************************
  141. BOOTSTRAP-SLIDER SOURCE CODE
  142. **************************************************/
  143. (function( $ ) {
  144. var ErrorMsgs = {
  145. formatInvalidInputErrorMsg : function(input) {
  146. return "Invalid input value '" + input + "' passed in";
  147. },
  148. 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"
  149. };
  150. /*************************************************
  151. CONSTRUCTOR
  152. **************************************************/
  153. var Slider = function(element, options) {
  154. createNewSlider.call(this, element, options);
  155. return this;
  156. };
  157. function createNewSlider(element, options) {
  158. /*************************************************
  159. Create Markup
  160. **************************************************/
  161. if(typeof element === "string") {
  162. this.element = document.querySelector(element);
  163. } else if(element instanceof HTMLElement) {
  164. this.element = element;
  165. }
  166. var origWidth = this.element.style.width;
  167. var updateSlider = false;
  168. var parent = this.element.parentNode;
  169. var sliderTrackSelection;
  170. var sliderMinHandle;
  171. var sliderMaxHandle;
  172. if (this.sliderElem) {
  173. updateSlider = true;
  174. } else {
  175. /* Create elements needed for slider */
  176. this.sliderElem = document.createElement("div");
  177. this.sliderElem.className = "slider";
  178. /* Create slider track elements */
  179. var sliderTrack = document.createElement("div");
  180. sliderTrack.className = "slider-track";
  181. sliderTrackSelection = document.createElement("div");
  182. sliderTrackSelection.className = "slider-selection";
  183. sliderMinHandle = document.createElement("div");
  184. sliderMinHandle.className = "slider-handle min-slider-handle";
  185. sliderMaxHandle = document.createElement("div");
  186. sliderMaxHandle.className = "slider-handle max-slider-handle";
  187. sliderTrack.appendChild(sliderTrackSelection);
  188. sliderTrack.appendChild(sliderMinHandle);
  189. sliderTrack.appendChild(sliderMaxHandle);
  190. var createAndAppendTooltipSubElements = function(tooltipElem) {
  191. var arrow = document.createElement("div");
  192. arrow.className = "tooltip-arrow";
  193. var inner = document.createElement("div");
  194. inner.className = "tooltip-inner";
  195. tooltipElem.appendChild(arrow);
  196. tooltipElem.appendChild(inner);
  197. };
  198. /* Create tooltip elements */
  199. var sliderTooltip = document.createElement("div");
  200. sliderTooltip.className = "tooltip tooltip-main";
  201. createAndAppendTooltipSubElements(sliderTooltip);
  202. var sliderTooltipMin = document.createElement("div");
  203. sliderTooltipMin.className = "tooltip tooltip-min";
  204. createAndAppendTooltipSubElements(sliderTooltipMin);
  205. var sliderTooltipMax = document.createElement("div");
  206. sliderTooltipMax.className = "tooltip tooltip-max";
  207. createAndAppendTooltipSubElements(sliderTooltipMax);
  208. /* Append components to sliderElem */
  209. this.sliderElem.appendChild(sliderTrack);
  210. this.sliderElem.appendChild(sliderTooltip);
  211. this.sliderElem.appendChild(sliderTooltipMin);
  212. this.sliderElem.appendChild(sliderTooltipMax);
  213. /* Append slider element to parent container, right before the original <input> element */
  214. parent.insertBefore(this.sliderElem, this.element);
  215. /* Hide original <input> element */
  216. this.element.style.display = "none";
  217. }
  218. /* If JQuery exists, cache JQ references */
  219. if($) {
  220. this.$element = $(this.element);
  221. this.$sliderElem = $(this.sliderElem);
  222. }
  223. /*************************************************
  224. Process Options
  225. **************************************************/
  226. options = options ? options : {};
  227. var optionTypes = Object.keys(this.defaultOptions);
  228. for(var i = 0; i < optionTypes.length; i++) {
  229. var optName = optionTypes[i];
  230. // First check if an option was passed in via the constructor
  231. var val = options[optName];
  232. // If no data attrib, then check data atrributes
  233. val = (typeof val !== 'undefined') ? val : getDataAttrib(this.element, optName);
  234. // Finally, if nothing was specified, use the defaults
  235. val = (val !== null) ? val : this.defaultOptions[optName];
  236. // Set all options on the instance of the Slider
  237. if(!this.options) {
  238. this.options = {};
  239. }
  240. this.options[optName] = val;
  241. }
  242. function getDataAttrib(element, optName) {
  243. var dataName = "data-slider-" + optName;
  244. var dataValString = element.getAttribute(dataName);
  245. try {
  246. return JSON.parse(dataValString);
  247. }
  248. catch(err) {
  249. return dataValString;
  250. }
  251. }
  252. /*************************************************
  253. Setup
  254. **************************************************/
  255. this.eventToCallbackMap = {};
  256. this.sliderElem.id = this.options.id;
  257. this.touchCapable = 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);
  258. this.tooltip = this.sliderElem.querySelector('.tooltip-main');
  259. this.tooltipInner = this.tooltip.querySelector('.tooltip-inner');
  260. this.tooltip_min = this.sliderElem.querySelector('.tooltip-min');
  261. this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner');
  262. this.tooltip_max = this.sliderElem.querySelector('.tooltip-max');
  263. this.tooltipInner_max= this.tooltip_max.querySelector('.tooltip-inner');
  264. if (updateSlider === true) {
  265. // Reset classes
  266. this._removeClass(this.sliderElem, 'slider-horizontal');
  267. this._removeClass(this.sliderElem, 'slider-vertical');
  268. this._removeClass(this.tooltip, 'hide');
  269. this._removeClass(this.tooltip_min, 'hide');
  270. this._removeClass(this.tooltip_max, 'hide');
  271. // Undo existing inline styles for track
  272. ["left", "top", "width", "height"].forEach(function(prop) {
  273. this._removeProperty(this.trackSelection, prop);
  274. }, this);
  275. // Undo inline styles on handles
  276. [this.handle1, this.handle2].forEach(function(handle) {
  277. this._removeProperty(handle, 'left');
  278. this._removeProperty(handle, 'top');
  279. }, this);
  280. // Undo inline styles and classes on tooltips
  281. [this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function(tooltip) {
  282. this._removeProperty(tooltip, 'left');
  283. this._removeProperty(tooltip, 'top');
  284. this._removeProperty(tooltip, 'margin-left');
  285. this._removeProperty(tooltip, 'margin-top');
  286. this._removeClass(tooltip, 'right');
  287. this._removeClass(tooltip, 'top');
  288. }, this);
  289. }
  290. if(this.options.orientation === 'vertical') {
  291. this._addClass(this.sliderElem,'slider-vertical');
  292. this.stylePos = 'top';
  293. this.mousePos = 'pageY';
  294. this.sizePos = 'offsetHeight';
  295. this._addClass(this.tooltip, 'right');
  296. this.tooltip.style.left = '100%';
  297. this._addClass(this.tooltip_min, 'right');
  298. this.tooltip_min.style.left = '100%';
  299. this._addClass(this.tooltip_max, 'right');
  300. this.tooltip_max.style.left = '100%';
  301. } else {
  302. this._addClass(this.sliderElem, 'slider-horizontal');
  303. this.sliderElem.style.width = origWidth;
  304. this.options.orientation = 'horizontal';
  305. this.stylePos = 'left';
  306. this.mousePos = 'pageX';
  307. this.sizePos = 'offsetWidth';
  308. this._addClass(this.tooltip, 'top');
  309. this.tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px';
  310. this._addClass(this.tooltip_min, 'top');
  311. this.tooltip_min.style.top = -this.tooltip_min.outerHeight - 14 + 'px';
  312. this._addClass(this.tooltip_max, 'top');
  313. this.tooltip_max.style.top = -this.tooltip_max.outerHeight - 14 + 'px';
  314. }
  315. if (this.options.value instanceof Array) {
  316. this.options.range = true;
  317. } else if (this.options.range) {
  318. // User wants a range, but value is not an array
  319. this.options.value = [this.options.value, this.options.max];
  320. }
  321. this.trackSelection = sliderTrackSelection || this.trackSelection;
  322. if (this.options.selection === 'none') {
  323. this._addClass(this.trackSelection, 'hide');
  324. }
  325. this.handle1 = sliderMinHandle || this.handle1;
  326. this.handle2 = sliderMaxHandle || this.handle2;
  327. if (updateSlider === true) {
  328. // Reset classes
  329. this._removeClass(this.handle1, 'round triangle');
  330. this._removeClass(this.handle2, 'round triangle hide');
  331. }
  332. var availableHandleModifiers = ['round', 'triangle', 'custom'];
  333. var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1;
  334. if (isValidHandleType) {
  335. this._addClass(this.handle1, this.options.handle);
  336. this._addClass(this.handle2, this.options.handle);
  337. }
  338. this.offset = this._offset(this.sliderElem);
  339. this.size = this.sliderElem[this.sizePos];
  340. this.setValue(this.options.value);
  341. /******************************************
  342. Bind Event Listeners
  343. ******************************************/
  344. // Bind keyboard handlers
  345. this.handle1Keydown = this._keydown.bind(this, 0);
  346. this.handle1.addEventListener("keydown", this.handle1Keydown, false);
  347. this.handle2Keydown = this._keydown.bind(this, 0);
  348. this.handle2.addEventListener("keydown", this.handle2Keydown, false);
  349. if (this.touchCapable) {
  350. // Bind touch handlers
  351. this.mousedown = this._mousedown.bind(this);
  352. this.sliderElem.addEventListener("touchstart", this.mousedown, false);
  353. } else {
  354. // Bind mouse handlers
  355. this.mousedown = this._mousedown.bind(this);
  356. this.sliderElem.addEventListener("mousedown", this.mousedown, false);
  357. }
  358. // Bind tooltip-related handlers
  359. if(this.options.tooltip === 'hide') {
  360. this._addClass(this.tooltip, 'hide');
  361. this._addClass(this.tooltip_min, 'hide');
  362. this._addClass(this.tooltip_max, 'hide');
  363. } else if(this.options.tooltip === 'always') {
  364. this._showTooltip();
  365. this._alwaysShowTooltip = true;
  366. } else {
  367. this.showTooltip = this._showTooltip.bind(this);
  368. this.hideTooltip = this._hideTooltip.bind(this);
  369. this.sliderElem.addEventListener("mouseenter", this.showTooltip, false);
  370. this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false);
  371. this.handle1.addEventListener("focus", this.showTooltip, false);
  372. this.handle1.addEventListener("blur", this.hideTooltip, false);
  373. this.handle2.addEventListener("focus", this.showTooltip, false);
  374. this.handle2.addEventListener("blur", this.hideTooltip, false);
  375. }
  376. if(this.options.enabled) {
  377. this.enable();
  378. } else {
  379. this.disable();
  380. }
  381. }
  382. /*************************************************
  383. INSTANCE PROPERTIES/METHODS
  384. - Any methods bound to the prototype are considered
  385. part of the plugin's `public` interface
  386. **************************************************/
  387. Slider.prototype = {
  388. _init: function() {}, // NOTE: Must exist to support bridget
  389. constructor: Slider,
  390. defaultOptions: {
  391. id: "",
  392. min: 0,
  393. max: 10,
  394. step: 1,
  395. precision: 0,
  396. orientation: 'horizontal',
  397. value: 5,
  398. range: false,
  399. selection: 'before',
  400. tooltip: 'show',
  401. tooltip_split: false,
  402. handle: 'round',
  403. reversed: false,
  404. enabled: true,
  405. formatter: function(val) {
  406. if(val instanceof Array) {
  407. return val[0] + " : " + val[1];
  408. } else {
  409. return val;
  410. }
  411. },
  412. natural_arrow_keys: false
  413. },
  414. over: false,
  415. inDrag: false,
  416. getValue: function() {
  417. if (this.options.range) {
  418. return this.options.value;
  419. }
  420. return this.options.value[0];
  421. },
  422. setValue: function(val, triggerSlideEvent) {
  423. if (!val) {
  424. val = 0;
  425. }
  426. this.options.value = this._validateInputValue(val);
  427. var applyPrecision = this._applyPrecision.bind(this);
  428. if (this.options.range) {
  429. this.options.value[0] = applyPrecision(this.options.value[0]);
  430. this.options.value[1] = applyPrecision(this.options.value[1]);
  431. this.options.value[0] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[0]));
  432. this.options.value[1] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[1]));
  433. } else {
  434. this.options.value = applyPrecision(this.options.value);
  435. this.options.value = [ Math.max(this.options.min, Math.min(this.options.max, this.options.value))];
  436. this._addClass(this.handle2, 'hide');
  437. if (this.options.selection === 'after') {
  438. this.options.value[1] = this.options.max;
  439. } else {
  440. this.options.value[1] = this.options.min;
  441. }
  442. }
  443. this.diff = this.options.max - this.options.min;
  444. if (this.diff > 0) {
  445. this.percentage = [
  446. (this.options.value[0] - this.options.min) * 100 / this.diff,
  447. (this.options.value[1] - this.options.min) * 100 / this.diff,
  448. this.options.step * 100 / this.diff
  449. ];
  450. } else {
  451. this.percentage = [0, 0, 100];
  452. }
  453. this._layout();
  454. var sliderValue = this.options.range ? this.options.value : this.options.value[0];
  455. this._setDataVal(sliderValue);
  456. if(triggerSlideEvent === true) {
  457. this._trigger('slide', sliderValue);
  458. }
  459. return this;
  460. },
  461. destroy: function(){
  462. // Remove event handlers on slider elements
  463. this._removeSliderEventHandlers();
  464. // Remove the slider from the DOM
  465. this.sliderElem.parentNode.removeChild(this.sliderElem);
  466. /* Show original <input> element */
  467. this.element.style.display = "";
  468. // Clear out custom event bindings
  469. this._cleanUpEventCallbacksMap();
  470. // Remove data values
  471. this.element.removeAttribute("data");
  472. // Remove JQuery handlers/data
  473. if($) {
  474. this._unbindJQueryEventHandlers();
  475. this.$element.removeData('slider');
  476. }
  477. },
  478. disable: function() {
  479. this.options.enabled = false;
  480. this.handle1.removeAttribute("tabindex");
  481. this.handle2.removeAttribute("tabindex");
  482. this._addClass(this.sliderElem, 'slider-disabled');
  483. this._trigger('slideDisabled');
  484. return this;
  485. },
  486. enable: function() {
  487. this.options.enabled = true;
  488. this.handle1.setAttribute("tabindex", 0);
  489. this.handle2.setAttribute("tabindex", 0);
  490. this._removeClass(this.sliderElem, 'slider-disabled');
  491. this._trigger('slideEnabled');
  492. return this;
  493. },
  494. toggle: function() {
  495. if(this.options.enabled) {
  496. this.disable();
  497. } else {
  498. this.enable();
  499. }
  500. return this;
  501. },
  502. isEnabled: function() {
  503. return this.options.enabled;
  504. },
  505. on: function(evt, callback) {
  506. if($) {
  507. this.$element.on(evt, callback);
  508. this.$sliderElem.on(evt, callback);
  509. } else {
  510. this._bindNonQueryEventHandler(evt, callback);
  511. }
  512. return this;
  513. },
  514. getAttribute: function(attribute) {
  515. if(attribute) {
  516. return this.options[attribute];
  517. } else {
  518. return this.options;
  519. }
  520. },
  521. setAttribute: function(attribute, value) {
  522. this.options[attribute] = value;
  523. return this;
  524. },
  525. refresh: function() {
  526. this._removeSliderEventHandlers();
  527. createNewSlider.call(this, this.element, this.options);
  528. if($) {
  529. // Bind new instance of slider to the element
  530. $.data(this.element, 'slider', this);
  531. }
  532. return this;
  533. },
  534. /******************************+
  535. HELPERS
  536. - Any method that is not part of the public interface.
  537. - Place it underneath this comment block and write its signature like so:
  538. _fnName : function() {...}
  539. ********************************/
  540. _removeSliderEventHandlers: function() {
  541. // Remove event listeners from handle1
  542. this.handle1.removeEventListener("keydown", this.handle1Keydown, false);
  543. this.handle1.removeEventListener("focus", this.showTooltip, false);
  544. this.handle1.removeEventListener("blur", this.hideTooltip, false);
  545. // Remove event listeners from handle2
  546. this.handle2.removeEventListener("keydown", this.handle2Keydown, false);
  547. this.handle2.removeEventListener("focus", this.handle2Keydown, false);
  548. this.handle2.removeEventListener("blur", this.handle2Keydown, false);
  549. // Remove event listeners from sliderElem
  550. this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false);
  551. this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false);
  552. this.sliderElem.removeEventListener("touchstart", this.mousedown, false);
  553. this.sliderElem.removeEventListener("mousedown", this.mousedown, false);
  554. },
  555. _bindNonQueryEventHandler: function(evt, callback) {
  556. if(this.eventToCallbackMap[evt]===undefined) {
  557. this.eventToCallbackMap[evt] = [];
  558. }
  559. this.eventToCallbackMap[evt].push(callback);
  560. },
  561. _cleanUpEventCallbacksMap: function() {
  562. var eventNames = Object.keys(this.eventToCallbackMap);
  563. for(var i = 0; i < eventNames.length; i++) {
  564. var eventName = eventNames[i];
  565. this.eventToCallbackMap[eventName] = null;
  566. }
  567. },
  568. _showTooltip: function() {
  569. if (this.options.tooltip_split === false ){
  570. this._addClass(this.tooltip, 'in');
  571. } else {
  572. this._addClass(this.tooltip_min, 'in');
  573. this._addClass(this.tooltip_max, 'in');
  574. }
  575. this.over = true;
  576. },
  577. _hideTooltip: function() {
  578. if (this.inDrag === false && this.alwaysShowTooltip !== true) {
  579. this._removeClass(this.tooltip, 'in');
  580. this._removeClass(this.tooltip_min, 'in');
  581. this._removeClass(this.tooltip_max, 'in');
  582. }
  583. this.over = false;
  584. },
  585. _layout: function() {
  586. var positionPercentages;
  587. if(this.options.reversed) {
  588. positionPercentages = [ 100 - this.percentage[0], this.percentage[1] ];
  589. } else {
  590. positionPercentages = [ this.percentage[0], this.percentage[1] ];
  591. }
  592. this.handle1.style[this.stylePos] = positionPercentages[0]+'%';
  593. this.handle2.style[this.stylePos] = positionPercentages[1]+'%';
  594. if (this.options.orientation === 'vertical') {
  595. this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
  596. this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
  597. } else {
  598. this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
  599. this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
  600. var offset_min = this.tooltip_min.getBoundingClientRect();
  601. var offset_max = this.tooltip_max.getBoundingClientRect();
  602. if (offset_min.right > offset_max.left) {
  603. this._removeClass(this.tooltip_max, 'top');
  604. this._addClass(this.tooltip_max, 'bottom');
  605. this.tooltip_max.style.top = 18 + 'px';
  606. } else {
  607. this._removeClass(this.tooltip_max, 'bottom');
  608. this._addClass(this.tooltip_max, 'top');
  609. this.tooltip_max.style.top = -30 + 'px';
  610. }
  611. }
  612. var formattedTooltipVal;
  613. if (this.options.range) {
  614. formattedTooltipVal = this.options.formatter(this.options.value);
  615. this._setText(this.tooltipInner, formattedTooltipVal);
  616. this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0])/2 + '%';
  617. if (this.options.orientation === 'vertical') {
  618. this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
  619. } else {
  620. this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
  621. }
  622. if (this.options.orientation === 'vertical') {
  623. this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
  624. } else {
  625. this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
  626. }
  627. var innerTooltipMinText = this.options.formatter(this.options.value[0]);
  628. this._setText(this.tooltipInner_min, innerTooltipMinText);
  629. var innerTooltipMaxText = this.options.formatter(this.options.value[1]);
  630. this._setText(this.tooltipInner_max, innerTooltipMaxText);
  631. this.tooltip_min.style[this.stylePos] = positionPercentages[0] + '%';
  632. if (this.options.orientation === 'vertical') {
  633. this._css(this.tooltip_min, 'margin-top', -this.tooltip_min.offsetHeight / 2 + 'px');
  634. } else {
  635. this._css(this.tooltip_min, 'margin-left', -this.tooltip_min.offsetWidth / 2 + 'px');
  636. }
  637. this.tooltip_max.style[this.stylePos] = positionPercentages[1] + '%';
  638. if (this.options.orientation === 'vertical') {
  639. this._css(this.tooltip_max, 'margin-top', -this.tooltip_max.offsetHeight / 2 + 'px');
  640. } else {
  641. this._css(this.tooltip_max, 'margin-left', -this.tooltip_max.offsetWidth / 2 + 'px');
  642. }
  643. } else {
  644. formattedTooltipVal = this.options.formatter(this.options.value[0]);
  645. this._setText(this.tooltipInner, formattedTooltipVal);
  646. this.tooltip.style[this.stylePos] = positionPercentages[0] + '%';
  647. if (this.options.orientation === 'vertical') {
  648. this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
  649. } else {
  650. this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
  651. }
  652. }
  653. },
  654. _removeProperty: function(element, prop) {
  655. if (element.style.removeProperty) {
  656. element.style.removeProperty(prop);
  657. } else {
  658. element.style.removeAttribute(prop);
  659. }
  660. },
  661. _mousedown: function(ev) {
  662. if(!this.options.enabled) {
  663. return false;
  664. }
  665. this._triggerFocusOnHandle();
  666. this.offset = this._offset(this.sliderElem);
  667. this.size = this.sliderElem[this.sizePos];
  668. var percentage = this._getPercentage(ev);
  669. if (this.options.range) {
  670. var diff1 = Math.abs(this.percentage[0] - percentage);
  671. var diff2 = Math.abs(this.percentage[1] - percentage);
  672. this.dragged = (diff1 < diff2) ? 0 : 1;
  673. } else {
  674. this.dragged = 0;
  675. }
  676. this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
  677. this._layout();
  678. this.mousemove = this._mousemove.bind(this);
  679. this.mouseup = this._mouseup.bind(this);
  680. if (this.touchCapable) {
  681. // Touch: Bind touch events:
  682. document.addEventListener("touchmove", this.mousemove, false);
  683. document.addEventListener("touchend", this.mouseup, false);
  684. } else {
  685. // Bind mouse events:
  686. document.addEventListener("mousemove", this.mousemove, false);
  687. document.addEventListener("mouseup", this.mouseup, false);
  688. }
  689. this.inDrag = true;
  690. var val = this._calculateValue();
  691. this._trigger('slideStart', val);
  692. this._setDataVal(val);
  693. this.setValue(val);
  694. this._pauseEvent(ev);
  695. return true;
  696. },
  697. _triggerFocusOnHandle: function(handleIdx) {
  698. if(handleIdx === 0) {
  699. this.handle1.focus();
  700. }
  701. if(handleIdx === 1) {
  702. this.handle2.focus();
  703. }
  704. },
  705. _keydown: function(handleIdx, ev) {
  706. if(!this.options.enabled) {
  707. return false;
  708. }
  709. var dir;
  710. switch (ev.keyCode) {
  711. case 37: // left
  712. case 40: // down
  713. dir = -1;
  714. break;
  715. case 39: // right
  716. case 38: // up
  717. dir = 1;
  718. break;
  719. }
  720. if (!dir) {
  721. return;
  722. }
  723. // use natural arrow keys instead of from min to max
  724. if (this.options.natural_arrow_keys) {
  725. var ifVerticalAndNotReversed = (this.options.orientation === 'vertical' && !this.options.reversed);
  726. var ifHorizontalAndReversed = (this.options.orientation === 'horizontal' && this.options.reversed);
  727. if (ifVerticalAndNotReversed || ifHorizontalAndReversed) {
  728. dir = dir * -1;
  729. }
  730. }
  731. var oneStepValuePercentageChange = dir * this.percentage[2];
  732. var percentage = this.percentage[handleIdx] + oneStepValuePercentageChange;
  733. if (percentage > 100) {
  734. percentage = 100;
  735. } else if (percentage < 0) {
  736. percentage = 0;
  737. }
  738. this.dragged = handleIdx;
  739. this._adjustPercentageForRangeSliders(percentage);
  740. this.percentage[this.dragged] = percentage;
  741. this._layout();
  742. var val = this._calculateValue();
  743. this._trigger('slideStart', val);
  744. this._setDataVal(val);
  745. this.setValue(val, true);
  746. this._trigger('slideStop', val);
  747. this._setDataVal(val);
  748. this._pauseEvent(ev);
  749. return false;
  750. },
  751. _pauseEvent: function(ev) {
  752. if(ev.stopPropagation) {
  753. ev.stopPropagation();
  754. }
  755. if(ev.preventDefault) {
  756. ev.preventDefault();
  757. }
  758. ev.cancelBubble=true;
  759. ev.returnValue=false;
  760. },
  761. _mousemove: function(ev) {
  762. if(!this.options.enabled) {
  763. return false;
  764. }
  765. var percentage = this._getPercentage(ev);
  766. this._adjustPercentageForRangeSliders(percentage);
  767. this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
  768. this._layout();
  769. var val = this._calculateValue();
  770. this.setValue(val, true);
  771. return false;
  772. },
  773. _adjustPercentageForRangeSliders: function(percentage) {
  774. if (this.options.range) {
  775. if (this.dragged === 0 && this.percentage[1] < percentage) {
  776. this.percentage[0] = this.percentage[1];
  777. this.dragged = 1;
  778. } else if (this.dragged === 1 && this.percentage[0] > percentage) {
  779. this.percentage[1] = this.percentage[0];
  780. this.dragged = 0;
  781. }
  782. }
  783. },
  784. _mouseup: function() {
  785. if(!this.options.enabled) {
  786. return false;
  787. }
  788. if (this.touchCapable) {
  789. // Touch: Unbind touch event handlers:
  790. document.removeEventListener("touchmove", this.mousemove, false);
  791. document.removeEventListener("touchend", this.mouseup, false);
  792. } else {
  793. // Unbind mouse event handlers:
  794. document.removeEventListener("mousemove", this.mousemove, false);
  795. document.removeEventListener("mouseup", this.mouseup, false);
  796. }
  797. this.inDrag = false;
  798. if (this.over === false) {
  799. this._hideTooltip();
  800. }
  801. var val = this._calculateValue();
  802. this._layout();
  803. this._setDataVal(val);
  804. this._trigger('slideStop', val);
  805. return false;
  806. },
  807. _calculateValue: function() {
  808. var val;
  809. if (this.options.range) {
  810. val = [this.options.min,this.options.max];
  811. if (this.percentage[0] !== 0){
  812. val[0] = (Math.max(this.options.min, this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step));
  813. val[0] = this._applyPrecision(val[0]);
  814. }
  815. if (this.percentage[1] !== 100){
  816. val[1] = (Math.min(this.options.max, this.options.min + Math.round((this.diff * this.percentage[1]/100)/this.options.step)*this.options.step));
  817. val[1] = this._applyPrecision(val[1]);
  818. }
  819. this.options.value = val;
  820. } else {
  821. val = (this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step);
  822. if (val < this.options.min) {
  823. val = this.options.min;
  824. }
  825. else if (val > this.options.max) {
  826. val = this.options.max;
  827. }
  828. val = parseFloat(val);
  829. val = this._applyPrecision(val);
  830. this.options.value = [val, this.options.value[1]];
  831. }
  832. return val;
  833. },
  834. _applyPrecision: function(val) {
  835. var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.step);
  836. return this._applyToFixedAndParseFloat(val, precision);
  837. },
  838. _getNumDigitsAfterDecimalPlace: function(num) {
  839. var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
  840. if (!match) { return 0; }
  841. return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
  842. },
  843. _applyToFixedAndParseFloat: function(num, toFixedInput) {
  844. var truncatedNum = num.toFixed(toFixedInput);
  845. return parseFloat(truncatedNum);
  846. },
  847. /*
  848. Credits to Mike Samuel for the following method!
  849. Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
  850. */
  851. _getPercentage: function(ev) {
  852. if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) {
  853. ev = ev.touches[0];
  854. }
  855. var percentage = (ev[this.mousePos] - this.offset[this.stylePos])*100/this.size;
  856. percentage = Math.round(percentage/this.percentage[2])*this.percentage[2];
  857. return Math.max(0, Math.min(100, percentage));
  858. },
  859. _validateInputValue: function(val) {
  860. if(typeof val === 'number') {
  861. return val;
  862. } else if(val instanceof Array) {
  863. this._validateArray(val);
  864. return val;
  865. } else {
  866. throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(val) );
  867. }
  868. },
  869. _validateArray: function(val) {
  870. for(var i = 0; i < val.length; i++) {
  871. var input = val[i];
  872. if (typeof input !== 'number') { throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(input) ); }
  873. }
  874. },
  875. _setDataVal: function(val) {
  876. var value = "value: '" + val + "'";
  877. this.element.setAttribute('data', value);
  878. this.element.setAttribute('value', val);
  879. },
  880. _trigger: function(evt, val) {
  881. val = val || undefined;
  882. var callbackFnArray = this.eventToCallbackMap[evt];
  883. if(callbackFnArray && callbackFnArray.length) {
  884. for(var i = 0; i < callbackFnArray.length; i++) {
  885. var callbackFn = callbackFnArray[i];
  886. callbackFn(val);
  887. }
  888. }
  889. /* If JQuery exists, trigger JQuery events */
  890. if($) {
  891. this._triggerJQueryEvent(evt, val);
  892. }
  893. },
  894. _triggerJQueryEvent: function(evt, val) {
  895. var eventData = {
  896. type: evt,
  897. value: val
  898. };
  899. this.$element.trigger(eventData);
  900. this.$sliderElem.trigger(eventData);
  901. },
  902. _unbindJQueryEventHandlers: function() {
  903. this.$element.off();
  904. this.$sliderElem.off();
  905. },
  906. _setText: function(element, text) {
  907. if(typeof element.innerText !== "undefined") {
  908. element.innerText = text;
  909. } else if(typeof element.textContent !== "undefined") {
  910. element.textContent = text;
  911. }
  912. },
  913. _removeClass: function(element, classString) {
  914. var classes = classString.split(" ");
  915. var newClasses = element.className;
  916. for(var i = 0; i < classes.length; i++) {
  917. var classTag = classes[i];
  918. var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
  919. newClasses = newClasses.replace(regex, " ");
  920. }
  921. element.className = newClasses.trim();
  922. },
  923. _addClass: function(element, classString) {
  924. var classes = classString.split(" ");
  925. var newClasses = element.className;
  926. for(var i = 0; i < classes.length; i++) {
  927. var classTag = classes[i];
  928. var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
  929. var ifClassExists = regex.test(newClasses);
  930. if(!ifClassExists) {
  931. newClasses += " " + classTag;
  932. }
  933. }
  934. element.className = newClasses.trim();
  935. },
  936. _offset: function (obj) {
  937. var ol = 0;
  938. var ot = 0;
  939. if (obj.offsetParent) {
  940. do {
  941. ol += obj.offsetLeft;
  942. ot += obj.offsetTop;
  943. } while (obj = obj.offsetParent);
  944. }
  945. return {
  946. left: ol,
  947. top: ot
  948. };
  949. },
  950. _css: function(elementRef, styleName, value) {
  951. elementRef.style[styleName] = value;
  952. }
  953. };
  954. /*********************************
  955. Attach to global namespace
  956. *********************************/
  957. if($) {
  958. var namespace = $.fn.slider ? 'bootstrapSlider' : 'slider';
  959. $.bridget(namespace, Slider);
  960. } else {
  961. window.Slider = Slider;
  962. }
  963. })( $ );
  964. })( window.jQuery );