bootstrap-slider.js 35 KB

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