jquery.event.scroll.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * jQuery extension, add support `scrollstart` and `scrollend` events.
  3. *
  4. * @author RubaXa <trash@rubaxa.org>
  5. * @github https://gist.github.com/RubaXa/5568964
  6. * @license MIT
  7. *
  8. *
  9. * @settings
  10. * $.special.scrollend.delay = 300; // default ms
  11. *
  12. * @flags
  13. * $.isScrolled; // boolean
  14. *
  15. * @binding
  16. * $(window).bind('scrollstart scrollend', function (evt){
  17. * if( evt.type == 'scrollstart' ){
  18. * // logic
  19. * }
  20. * });
  21. *
  22. */
  23. (function ($){
  24. var
  25. ns = (new Date).getTime()
  26. , special = $.event.special
  27. , dispatch = $.event.handle || $.event.dispatch
  28. , scroll = 'scroll'
  29. , scrollStart = scroll + 'start'
  30. , scrollEnd = scroll + 'end'
  31. , nsScrollStart = scroll +'.'+ scrollStart + ns
  32. , nsScrollEnd = scroll +'.'+ scrollEnd + ns
  33. ;
  34. special.scrollstart = {
  35. setup: function (){
  36. var pid, handler = function (evt/**$.Event*/){
  37. if( pid == null ){
  38. evt.type = scrollStart;
  39. dispatch.apply(this, arguments);
  40. }
  41. else {
  42. clearTimeout(pid);
  43. }
  44. pid = setTimeout(function(){
  45. pid = null;
  46. }, special.scrollend.delay);
  47. };
  48. $(this).bind(nsScrollStart, handler);
  49. },
  50. teardown: function (){
  51. $(this).unbind(nsScrollStart);
  52. }
  53. };
  54. special.scrollend = {
  55. delay: 300,
  56. setup: function (){
  57. var pid, handler = function (evt/**$.Event*/){
  58. var _this = this, args = arguments;
  59. clearTimeout(pid);
  60. pid = setTimeout(function(){
  61. evt.type = scrollEnd;
  62. dispatch.apply(_this, args);
  63. }, special.scrollend.delay);
  64. };
  65. $(this).bind(nsScrollEnd, handler);
  66. },
  67. teardown: function (){
  68. $(this).unbind(nsScrollEnd);
  69. }
  70. };
  71. $.isScrolled = false;
  72. $(window).bind(scrollStart+' '+scrollEnd, function (evt/**Event*/){
  73. $.isScrolled = (evt.type == scrollStart);
  74. $('body')[$.isScrolled ? 'addClass' : 'removeClass']('is-scrolled');
  75. });
  76. })(jQuery);