Main Super Tables Resources Puzzles
  Search:
Most Popular Other Sites

Simulating onResizeEnd, onScrollEnd and onMousemoveEnd

I ran across an issue the other week where an onScroll JavaScript function was being called too often and I needed to figure out a way to execute it only when needed. Knowing that the code was mainly intended for post-scrolling execution, I came up with this idea* of setting and resetting a timeout again and again until the actual event finished and the set timeout fired the real code. So far it seems to be working great so I thought I'd share.

The following code will execute the intended onWhatever function once the user stops resizing, scrolling or moving the mouse ( depending on how it's used ). Please check out the demo pages to see the simulated events in action.

This script was successfully tested in Windows versions of Internet Explorer 5.5 - 7, Firefox 1.5 - 3, Opera 9 and Safari 3.

Demos

onResize vs Simulated onResizeEnd - Test Page onScroll vs Simulated onScrollEnd - Test Page onMousemove vs Simulated onMousemoveEnd - Test Page onResizeEnd, onScrollEnd, onMousemoveEnd:
var whateverEndFunc = function () {
    var delay = 50; // milliseconds
    var whateverTimeout;
    
    return function () {
        if (whateverTimeout) {
            clearTimeout(whateverTimeout);
        }
        
        whateverTimeout = setTimeout(function () {
            // YOUR [onResize, onScroll or onMousemove] CODE HERE
        }, delay);
    };
}();
 

If you decrease the variable delay the code inside of the timeout will be called more often and vice versa. To use this code, call it just like you would onResize, onScroll or onMousemove. Some basic examples:

window.onresize = function () {
    whateverEndFunc();
}

window.onscroll = function () {
    whateverEndFunc();
}

document.onmousemove = function () {
    whateverEndFunc();
}

* inspired by Ari Karp - who needs to make a damn blog : )

              

Comments

justin Posted on May 20, 2008 01:29:22 AM
Matt M Posted on May 20, 2008 05:43:36 AM
½title Posted on August 05, 2008 04:17:20 PM
Nickname:  ( required )
Email:  ( will not be shown - required )
Website:
Comments: