0

There are numerous questions on SO about custom jQuery events. Almost all of them only have answers suggesting the use of $.fn.extend().
Here is my script using $.fn.extend() to detect when an element has stopped scrolling:

$.fn.extend({
  scrollStopped: function (callback) {
    var $this = $(this)
    $this.scroll(function () {
      clearTimeout($this.data('scrollTimeout'))
      $this.data('scrollTimeout', setTimeout(callback.bind(this), 150))
    }.bind(this))
    return this
  }
})
$('element').scrollStopped(function () {
  alert('Scrolling has stopped')
})

Like the title of this question suggests, what I want, however, is not an event that has to be added with .scrollStopped(), but one that can be added with the .on() method, like so:

$('window').on('scrollStopped', function () {
  alert('Window has stopped scrolling')
})
$('div').on('scrollStopped', function () {
  alert('Div has stopped scrolling')
})

I've been scanning the jQuery source trying to find a way to do this. After copy-pasting a bunch of snippets for an hour or two, I decided to look for an answer on SO, which was surprisingly hard to find. This answer helped me a bit, but (like I said in the comments of that answer, one hour ago) the events that trigger the custom event there are hardcoded to the body and then sent to the elements to which the .on() method is bound.
There are two problems with the approach:

  • The event logic still isn't part of jQuery's internal structure. It's simply part of an event triggered by the body (not a deal-breaker per say)
  • Scroll events (like the one I'm trying to use) don't bubble, meaning that converting the events from keydown to scroll won't work

I've simplified the Fiddle from the answer here.

I know I could use a native event and set useCapture to true to capture all scroll events on the page, but seeing there are no answers anywhere on SO that explain how to do what I want, I think it's worthwhile to take a look at this.



The only reason I want to do this, is because I want to be able to write things like:

$(window).on('beforeunload scrollStopped', function () { savePageScroll() })

Instead of:

$(window)
  .on('beforeunload', function () { savePageScroll() })
  .scrollStopped(     function () { savePageScroll() })`
Gust van de Wal
  • 5,211
  • 1
  • 24
  • 48

0 Answers0