waves.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. /*!
  2. * Waves v0.7.5
  3. * http://fian.my.id/Waves
  4. *
  5. * Copyright 2014-2016 Alfiana E. Sibuea and other contributors
  6. * Released under the MIT license
  7. * https://github.com/fians/Waves/blob/master/LICENSE
  8. */
  9. ;(function (window, factory) {
  10. 'use strict';
  11. // AMD. Register as an anonymous module. Wrap in function so we have access
  12. // to root via `this`.
  13. if (typeof define === 'function' && define.amd) {
  14. define([], function () {
  15. return factory.apply(window);
  16. });
  17. }
  18. // Node. Does not work with strict CommonJS, but only CommonJS-like
  19. // environments that support module.exports, like Node.
  20. else if (typeof exports === 'object') {
  21. module.exports = factory.call(window);
  22. }
  23. // Browser globals.
  24. else {
  25. window.Waves = factory.call(window);
  26. }
  27. })(typeof global === 'object' ? global : this, function () {
  28. 'use strict';
  29. var Waves = Waves || {};
  30. var $$ = document.querySelectorAll.bind(document);
  31. var toString = Object.prototype.toString;
  32. var isTouchAvailable = 'ontouchstart' in window;
  33. // Find exact position of element
  34. function isWindow(obj) {
  35. return obj !== null && obj === obj.window;
  36. }
  37. function getWindow(elem) {
  38. return isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView;
  39. }
  40. function isObject(value) {
  41. var type = typeof value;
  42. return type === 'function' || type === 'object' && !!value;
  43. }
  44. function isDOMNode(obj) {
  45. return isObject(obj) && obj.nodeType > 0;
  46. }
  47. function getWavesElements(nodes) {
  48. var stringRepr = toString.call(nodes);
  49. if (stringRepr === '[object String]') {
  50. return $$(nodes);
  51. } else if (isObject(nodes) && /^\[object (Array|HTMLCollection|NodeList|Object)\]$/.test(stringRepr) && nodes.hasOwnProperty('length')) {
  52. return nodes;
  53. } else if (isDOMNode(nodes)) {
  54. return [nodes];
  55. }
  56. return [];
  57. }
  58. function offset(elem) {
  59. var docElem, win,
  60. box = {top: 0, left: 0},
  61. doc = elem && elem.ownerDocument;
  62. docElem = doc.documentElement;
  63. if (typeof elem.getBoundingClientRect !== typeof undefined) {
  64. box = elem.getBoundingClientRect();
  65. }
  66. win = getWindow(doc);
  67. return {
  68. top: box.top + win.pageYOffset - docElem.clientTop,
  69. left: box.left + win.pageXOffset - docElem.clientLeft
  70. };
  71. }
  72. function convertStyle(styleObj) {
  73. var style = '';
  74. for (var prop in styleObj) {
  75. if (styleObj.hasOwnProperty(prop)) {
  76. style += (prop + ':' + styleObj[prop] + ';');
  77. }
  78. }
  79. return style;
  80. }
  81. var Effect = {
  82. // Effect duration
  83. duration: 750,
  84. // Effect delay (check for scroll before showing effect)
  85. delay: 200,
  86. show: function (e, element, velocity) {
  87. // Disable right click
  88. if (e.button === 2) {
  89. return false;
  90. }
  91. element = element || this;
  92. // Create ripple
  93. var ripple = document.createElement('div');
  94. ripple.className = 'waves-ripple waves-rippling';
  95. element.appendChild(ripple);
  96. // Get click coordinate and element width
  97. var pos = offset(element);
  98. var relativeY = 0;
  99. var relativeX = 0;
  100. // Support for touch devices
  101. if ('touches' in e && e.touches.length) {
  102. relativeY = (e.touches[0].pageY - pos.top);
  103. relativeX = (e.touches[0].pageX - pos.left);
  104. }
  105. //Normal case
  106. else {
  107. relativeY = (e.pageY - pos.top);
  108. relativeX = (e.pageX - pos.left);
  109. }
  110. // Support for synthetic events
  111. relativeX = relativeX >= 0 ? relativeX : 0;
  112. relativeY = relativeY >= 0 ? relativeY : 0;
  113. var scale = 'scale(' + ((element.clientWidth / 100) * 3) + ')';
  114. var translate = 'translate(0,0)';
  115. if (velocity) {
  116. translate = 'translate(' + (velocity.x) + 'px, ' + (velocity.y) + 'px)';
  117. }
  118. // Attach data to element
  119. ripple.setAttribute('data-hold', Date.now());
  120. ripple.setAttribute('data-x', relativeX);
  121. ripple.setAttribute('data-y', relativeY);
  122. ripple.setAttribute('data-scale', scale);
  123. ripple.setAttribute('data-translate', translate);
  124. // Set ripple position
  125. var rippleStyle = {
  126. top: relativeY + 'px',
  127. left: relativeX + 'px'
  128. };
  129. ripple.classList.add('waves-notransition');
  130. ripple.setAttribute('style', convertStyle(rippleStyle));
  131. ripple.classList.remove('waves-notransition');
  132. // Scale the ripple
  133. rippleStyle['-webkit-transform'] = scale + ' ' + translate;
  134. rippleStyle['-moz-transform'] = scale + ' ' + translate;
  135. rippleStyle['-ms-transform'] = scale + ' ' + translate;
  136. rippleStyle['-o-transform'] = scale + ' ' + translate;
  137. rippleStyle.transform = scale + ' ' + translate;
  138. rippleStyle.opacity = '1';
  139. var duration = e.type === 'mousemove' ? 2500 : Effect.duration;
  140. rippleStyle['-webkit-transition-duration'] = duration + 'ms';
  141. rippleStyle['-moz-transition-duration'] = duration + 'ms';
  142. rippleStyle['-o-transition-duration'] = duration + 'ms';
  143. rippleStyle['transition-duration'] = duration + 'ms';
  144. ripple.setAttribute('style', convertStyle(rippleStyle));
  145. },
  146. hide: function (e, element) {
  147. element = element || this;
  148. var ripples = element.getElementsByClassName('waves-rippling');
  149. for (var i = 0, len = ripples.length; i < len; i++) {
  150. removeRipple(e, element, ripples[i]);
  151. }
  152. }
  153. };
  154. /**
  155. * Collection of wrapper for HTML element that only have single tag
  156. * like <input> and <img>
  157. */
  158. var TagWrapper = {
  159. // Wrap <input> tag so it can perform the effect
  160. input: function (element) {
  161. var parent = element.parentNode;
  162. // If input already have parent just pass through
  163. if (parent.tagName.toLowerCase() === 'i' && parent.classList.contains('waves-effect')) {
  164. return;
  165. }
  166. // Put element class and style to the specified parent
  167. var wrapper = document.createElement('i');
  168. wrapper.className = element.className + ' waves-input-wrapper';
  169. element.className = 'waves-button-input';
  170. // Put element as child
  171. parent.replaceChild(wrapper, element);
  172. wrapper.appendChild(element);
  173. // Apply element color and background color to wrapper
  174. var elementStyle = window.getComputedStyle(element, null);
  175. var color = elementStyle.color;
  176. var backgroundColor = elementStyle.backgroundColor;
  177. wrapper.setAttribute('style', 'color:' + color + ';background:' + backgroundColor);
  178. element.setAttribute('style', 'background-color:rgba(0,0,0,0);');
  179. },
  180. // Wrap <img> tag so it can perform the effect
  181. img: function (element) {
  182. var parent = element.parentNode;
  183. // If input already have parent just pass through
  184. if (parent.tagName.toLowerCase() === 'i' && parent.classList.contains('waves-effect')) {
  185. return;
  186. }
  187. // Put element as child
  188. var wrapper = document.createElement('i');
  189. parent.replaceChild(wrapper, element);
  190. wrapper.appendChild(element);
  191. }
  192. };
  193. /**
  194. * Hide the effect and remove the ripple. Must be
  195. * a separate function to pass the JSLint...
  196. */
  197. function removeRipple(e, el, ripple) {
  198. // Check if the ripple still exist
  199. if (!ripple) {
  200. return;
  201. }
  202. ripple.classList.remove('waves-rippling');
  203. var relativeX = ripple.getAttribute('data-x');
  204. var relativeY = ripple.getAttribute('data-y');
  205. var scale = ripple.getAttribute('data-scale');
  206. var translate = ripple.getAttribute('data-translate');
  207. // Get delay beetween mousedown and mouse leave
  208. var diff = Date.now() - Number(ripple.getAttribute('data-hold'));
  209. var delay = 350 - diff;
  210. if (delay < 0) {
  211. delay = 0;
  212. }
  213. if (e.type === 'mousemove') {
  214. delay = 150;
  215. }
  216. // Fade out ripple after delay
  217. var duration = e.type === 'mousemove' ? 2500 : Effect.duration;
  218. setTimeout(function () {
  219. var style = {
  220. top: relativeY + 'px',
  221. left: relativeX + 'px',
  222. opacity: '0',
  223. // Duration
  224. '-webkit-transition-duration': duration + 'ms',
  225. '-moz-transition-duration': duration + 'ms',
  226. '-o-transition-duration': duration + 'ms',
  227. 'transition-duration': duration + 'ms',
  228. '-webkit-transform': scale + ' ' + translate,
  229. '-moz-transform': scale + ' ' + translate,
  230. '-ms-transform': scale + ' ' + translate,
  231. '-o-transform': scale + ' ' + translate,
  232. 'transform': scale + ' ' + translate
  233. };
  234. ripple.setAttribute('style', convertStyle(style));
  235. setTimeout(function () {
  236. try {
  237. el.removeChild(ripple);
  238. } catch (e) {
  239. return false;
  240. }
  241. }, duration);
  242. }, delay);
  243. }
  244. /**
  245. * Disable mousedown event for 500ms during and after touch
  246. */
  247. var TouchHandler = {
  248. /* uses an integer rather than bool so there's no issues with
  249. * needing to clear timeouts if another touch event occurred
  250. * within the 500ms. Cannot mouseup between touchstart and
  251. * touchend, nor in the 500ms after touchend. */
  252. touches: 0,
  253. allowEvent: function (e) {
  254. var allow = true;
  255. if (/^(mousedown|mousemove)$/.test(e.type) && TouchHandler.touches) {
  256. allow = false;
  257. }
  258. return allow;
  259. },
  260. registerEvent: function (e) {
  261. var eType = e.type;
  262. if (eType === 'touchstart') {
  263. TouchHandler.touches += 1; // push
  264. } else if (/^(touchend|touchcancel)$/.test(eType)) {
  265. setTimeout(function () {
  266. if (TouchHandler.touches) {
  267. TouchHandler.touches -= 1; // pop after 500ms
  268. }
  269. }, 500);
  270. }
  271. }
  272. };
  273. /**
  274. * Delegated click handler for .waves-effect element.
  275. * returns null when .waves-effect element not in "click tree"
  276. */
  277. function getWavesEffectElement(e) {
  278. if (TouchHandler.allowEvent(e) === false) {
  279. return null;
  280. }
  281. var element = null;
  282. var target = e.target || e.srcElement;
  283. while (target.parentElement !== null) {
  284. if (target.classList.contains('waves-effect') && (!(target instanceof SVGElement))) {
  285. element = target;
  286. break;
  287. }
  288. target = target.parentElement;
  289. }
  290. return element;
  291. }
  292. /**
  293. * Bubble the click and show effect if .waves-effect elem was found
  294. */
  295. function showEffect(e) {
  296. // Disable effect if element has "disabled" property on it
  297. // In some cases, the event is not triggered by the current element
  298. // if (e.target.getAttribute('disabled') !== null) {
  299. // return;
  300. // }
  301. var element = getWavesEffectElement(e);
  302. if (element !== null) {
  303. // Make it sure the element has either disabled property, disabled attribute or 'disabled' class
  304. if (element.disabled || element.getAttribute('disabled') || element.classList.contains('disabled')) {
  305. return;
  306. }
  307. TouchHandler.registerEvent(e);
  308. if (e.type === 'touchstart' && Effect.delay) {
  309. var hidden = false;
  310. var timer = setTimeout(function () {
  311. timer = null;
  312. Effect.show(e, element);
  313. }, Effect.delay);
  314. var hideEffect = function (hideEvent) {
  315. // if touch hasn't moved, and effect not yet started: start effect now
  316. if (timer) {
  317. clearTimeout(timer);
  318. timer = null;
  319. Effect.show(e, element);
  320. }
  321. if (!hidden) {
  322. hidden = true;
  323. Effect.hide(hideEvent, element);
  324. }
  325. };
  326. var touchMove = function (moveEvent) {
  327. if (timer) {
  328. clearTimeout(timer);
  329. timer = null;
  330. }
  331. hideEffect(moveEvent);
  332. };
  333. element.addEventListener('touchmove', touchMove, false);
  334. element.addEventListener('touchend', hideEffect, false);
  335. element.addEventListener('touchcancel', hideEffect, false);
  336. } else {
  337. Effect.show(e, element);
  338. if (isTouchAvailable) {
  339. element.addEventListener('touchend', Effect.hide, false);
  340. element.addEventListener('touchcancel', Effect.hide, false);
  341. }
  342. element.addEventListener('mouseup', Effect.hide, false);
  343. element.addEventListener('mouseleave', Effect.hide, false);
  344. }
  345. }
  346. }
  347. Waves.init = function (options) {
  348. var body = document.body;
  349. options = options || {};
  350. if ('duration' in options) {
  351. Effect.duration = options.duration;
  352. }
  353. if ('delay' in options) {
  354. Effect.delay = options.delay;
  355. }
  356. if (isTouchAvailable) {
  357. body.addEventListener('touchstart', showEffect, false);
  358. body.addEventListener('touchcancel', TouchHandler.registerEvent, false);
  359. body.addEventListener('touchend', TouchHandler.registerEvent, false);
  360. }
  361. body.addEventListener('mousedown', showEffect, false);
  362. };
  363. /**
  364. * Attach Waves to dynamically loaded inputs, or add .waves-effect and other
  365. * waves classes to a set of elements. Set drag to true if the ripple mouseover
  366. * or skimming effect should be applied to the elements.
  367. */
  368. Waves.attach = function (elements, classes) {
  369. elements = getWavesElements(elements);
  370. if (toString.call(classes) === '[object Array]') {
  371. classes = classes.join(' ');
  372. }
  373. classes = classes ? ' ' + classes : '';
  374. var element, tagName;
  375. for (var i = 0, len = elements.length; i < len; i++) {
  376. element = elements[i];
  377. tagName = element.tagName.toLowerCase();
  378. if (['input', 'img'].indexOf(tagName) !== -1) {
  379. TagWrapper[tagName](element);
  380. element = element.parentElement;
  381. }
  382. if (element.className.indexOf('waves-effect') === -1) {
  383. element.className += ' waves-effect' + classes;
  384. }
  385. }
  386. };
  387. /**
  388. * Cause a ripple to appear in an element via code.
  389. */
  390. Waves.ripple = function (elements, options) {
  391. elements = getWavesElements(elements);
  392. var elementsLen = elements.length;
  393. options = options || {};
  394. options.wait = options.wait || 0;
  395. options.position = options.position || null; // default = centre of element
  396. if (elementsLen) {
  397. var element, pos, off, centre = {}, i = 0;
  398. var mousedown = {
  399. type: 'mousedown',
  400. button: 1
  401. };
  402. var hideRipple = function (mouseup, element) {
  403. return function () {
  404. Effect.hide(mouseup, element);
  405. };
  406. };
  407. for (; i < elementsLen; i++) {
  408. element = elements[i];
  409. pos = options.position || {
  410. x: element.clientWidth / 2,
  411. y: element.clientHeight / 2
  412. };
  413. off = offset(element);
  414. centre.x = off.left + pos.x;
  415. centre.y = off.top + pos.y;
  416. mousedown.pageX = centre.x;
  417. mousedown.pageY = centre.y;
  418. Effect.show(mousedown, element);
  419. if (options.wait >= 0 && options.wait !== null) {
  420. var mouseup = {
  421. type: 'mouseup',
  422. button: 1
  423. };
  424. setTimeout(hideRipple(mouseup, element), options.wait);
  425. }
  426. }
  427. }
  428. };
  429. /**
  430. * Remove all ripples from an element.
  431. */
  432. Waves.calm = function (elements) {
  433. elements = getWavesElements(elements);
  434. var mouseup = {
  435. type: 'mouseup',
  436. button: 1
  437. };
  438. for (var i = 0, len = elements.length; i < len; i++) {
  439. Effect.hide(mouseup, elements[i]);
  440. }
  441. };
  442. /**
  443. * Deprecated API fallback
  444. */
  445. Waves.displayEffect = function (options) {
  446. console.error('Waves.displayEffect() has been deprecated and will be removed in future version. Please use Waves.init() to initialize Waves effect');
  447. Waves.init(options);
  448. };
  449. return Waves;
  450. });