touche.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* global jQuery:true */
  2. (function() {
  3. 'use strict';
  4. var isTouch = 'ontouchstart' in window || 'msmaxtouchpoints' in window.navigator;
  5. function Touche(nodes) {
  6. // Doing this allows the developer to omit the `new` keyword from their calls to Touche
  7. if ( ! (this instanceof Touche)) {
  8. return new Touche( nodes );
  9. }
  10. if ( ! nodes) {
  11. throw new Error( 'No DOM elements passed into Touche' );
  12. }
  13. this.nodes = nodes;
  14. return this;
  15. }
  16. // Our own event handler
  17. Touche.prototype.on = function(event, fn) {
  18. var touchend, nodes = this.nodes,
  19. len = nodes.length,
  20. ev;
  21. if (isTouch && event === 'click') {
  22. touchend = true;
  23. }
  24. ev = function(el, event, fn) {
  25. var called, once = function() {
  26. if ( ! called && (called = true)) {
  27. fn.apply( this, arguments );
  28. }
  29. };
  30. el.addEventListener( event, once, false );
  31. if (touchend) {
  32. el.addEventListener( 'touchend', once, false );
  33. }
  34. };
  35. // NodeList or just a Node?
  36. if (len) {
  37. while (len--) {
  38. ev( nodes[len], event, fn );
  39. }
  40. } else {
  41. ev( nodes, event, fn );
  42. }
  43. return this;
  44. };
  45. // Expose Touche
  46. window.Touche = Touche;
  47. // Has the developer used jQuery?
  48. if (window.jQuery && isTouch) {
  49. var originalOnMethod = jQuery.fn.on,
  50. originalOffMethod = jQuery.fn.off;
  51. var replaceEventName = function (event) {
  52. if (event.slice( 0, 5 ) == 'click') {
  53. return event.replace( 'click', 'touchend' );
  54. }
  55. return event;
  56. }
  57. // Change event type and re-apply .on() method
  58. jQuery.fn.on = function() {
  59. // arguments[0] is the event name if provided
  60. if (typeof arguments[0] === "string") {
  61. arguments[0] = replaceEventName( arguments[0] );
  62. }
  63. originalOnMethod.apply( this, arguments );
  64. return this;
  65. };
  66. // Change event type and re-apply .off() method
  67. jQuery.fn.off = function() {
  68. // arguments[0] is the event name if provided
  69. if (typeof arguments[0] === "string") {
  70. arguments[0] = replaceEventName( arguments[0] );
  71. }
  72. originalOffMethod.apply( this, arguments );
  73. return this;
  74. };
  75. }
  76. })();