dragscroll.js 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * @fileoverview dragscroll - scroll area by dragging
  3. * @version 0.0.8
  4. *
  5. * @license MIT, see http://github.com/asvd/dragscroll
  6. * @copyright 2015 asvd <heliosframework@gmail.com>
  7. */
  8. (function (root, factory) {
  9. if (typeof define === 'function' && define.amd) {
  10. define(['exports'], factory);
  11. } else if (typeof exports !== 'undefined') {
  12. factory(exports);
  13. } else {
  14. factory((root.dragscroll = {}));
  15. }
  16. }(this, function (exports) {
  17. var _window = window;
  18. var _document = document;
  19. var mousemove = 'mousemove';
  20. var mouseup = 'mouseup';
  21. var mousedown = 'mousedown';
  22. var EventListener = 'EventListener';
  23. var addEventListener = 'add'+EventListener;
  24. var removeEventListener = 'remove'+EventListener;
  25. var newScrollX, newScrollY;
  26. var dragged = [];
  27. var reset = function(i, el) {
  28. for (i = 0; i < dragged.length;) {
  29. el = dragged[i++];
  30. el = el.container || el;
  31. el[removeEventListener](mousedown, el.md, 0);
  32. _window[removeEventListener](mouseup, el.mu, 0);
  33. _window[removeEventListener](mousemove, el.mm, 0);
  34. }
  35. // cloning into array since HTMLCollection is updated dynamically
  36. dragged = [].slice.call(_document.getElementsByClassName('dragscroll'));
  37. for (i = 0; i < dragged.length;) {
  38. (function(el, lastClientX, lastClientY, pushed, scroller, cont){
  39. (cont = el.container || el)[addEventListener](
  40. mousedown,
  41. cont.md = function(e) {
  42. if (!el.hasAttribute('nochilddrag') ||
  43. _document.elementFromPoint(
  44. e.pageX, e.pageY
  45. ) == cont
  46. ) {
  47. pushed = 1;
  48. lastClientX = e.clientX;
  49. lastClientY = e.clientY;
  50. e.preventDefault();
  51. }
  52. }, 0
  53. );
  54. _window[addEventListener](
  55. mouseup, cont.mu = function() {pushed = 0;}, 0
  56. );
  57. _window[addEventListener](
  58. mousemove,
  59. cont.mm = function(e) {
  60. if (pushed) {
  61. (scroller = el.scroller||el).scrollLeft -=
  62. newScrollX = (- lastClientX + (lastClientX=e.clientX));
  63. scroller.scrollTop -=
  64. newScrollY = (- lastClientY + (lastClientY=e.clientY));
  65. if (el == _document.body) {
  66. (scroller = _document.documentElement).scrollLeft -= newScrollX;
  67. scroller.scrollTop -= newScrollY;
  68. }
  69. }
  70. }, 0
  71. );
  72. })(dragged[i++]);
  73. }
  74. }
  75. if (_document.readyState == 'complete') {
  76. reset();
  77. } else {
  78. _window[addEventListener]('load', reset, 0);
  79. }
  80. exports.reset = reset;
  81. }));