Search This Blog


JavaScript tip: on complete event

Recently I was fixing some issue in the JavaScipt event handler. Task was simple: to save user scroll position setting for the HTML control to the server.
Of course, it is possible to subscribe on the "scroll" event of the jQuery control and add a handler. But while user is scrolling it invokes event handler enormous number of times :-), so I need only "on scroll complete" event. And it took me some time to find one of the solutions.
If you need to have an "on complete" entry for some continuing event (like scrolling), described solution might help you.
Some event handler:

This code will write "scrolling..." to the console a lot of times while scrolling. In order to make it work just "on complete" we can add the timer function. Idea is simple: each time while scrolling it will cancel the timer function and then create it again. After the last scroll event (and after 1 sec) we will have an "on complete" function so it will write some message to the console.
EventHandler = function ($control) {
  if (!$control) {
    throw ("jQuery control is expected");

  this.$control = $control;
  this.scrollCompleteHandling = null;

EventHandler.prototype.setupHandlers = function () {
  var self = this;
  this.$control.bind("scroll", function () {
    if (self.scrollCompleteHandling) {
    self.scrollCompleteHandling = setTimeout(function () {
    }, 1000);
It might not be the best option, but still it works :-)

No comments:

Post a Comment