Skip to content

Instantly share code, notes, and snippets.

@milosdjakonovic
Created September 28, 2016 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save milosdjakonovic/fd50ee34c761c95d9df33e3c419b2cbb to your computer and use it in GitHub Desktop.
Save milosdjakonovic/fd50ee34c761c95d9df33e3c419b2cbb to your computer and use it in GitHub Desktop.
Register resize function - an easy way to register function for debounced execution with parameters
/**
*
* Usage example:
*
* $('#headerghost').css('height', $('header').outerHeight()-32);
*
* registerResizeFunction(function($header, $headerghost){
* $headerghost.css('height', $header.outerHeight()-32);
* }, $('header'), $('#headerghost'));
*
*
**/
(function(w, $){
function Debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
w.clearTimeout(timeout);
timeout = w.setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
var registeredResizeFunctions=[];
function registerResizeFunction(){
var fn = arguments[0],
args = [];
for(var i=0;i<arguments.length;i++){
if(i===0)continue;
args.push( arguments[i] );
}
registeredResizeFunctions.push({
"cb" : fn,
"args" : args
});
}
function executeRegisteredResizeFunctions(){
for(var i=0; i<registeredResizeFunctions.length;i++){
registeredResizeFunctions[i].cb.apply(this, registeredResizeFunctions[i].args );
}
}
$(w).on('resize', Debounce(executeRegisteredResizeFunctions,40));
})(window, window.jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment