bootstrap-slider.js 46 KB

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