Skip to content

Instantly share code, notes, and snippets.

@perpetual-hydrofoil
Last active June 28, 2016 18:43
Show Gist options
  • Save perpetual-hydrofoil/f14eeb12565db770bfc223643420df79 to your computer and use it in GitHub Desktop.
Save perpetual-hydrofoil/f14eeb12565db770bfc223643420df79 to your computer and use it in GitHub Desktop.
/* resize_function executes a function whenever the screensize changes.
by Jamieson Becker. Public Domain (do what you will)
requires jQuery or compatible.
*/
on_resize = function(f) {
var still_running = false;
var previous_height = 0;
var previous_width = 0;
if (!f) console.error("Please provide resize_function with a function");
$(window).resize(function() {
if (still_running) return;
still_running = true;
var height = $(window).height(); // New height
var width = $(window).width(); // New width
if (height != previous_height || width != previous_width) {
setTimeout(function() {
// get latest height and width at end
var height = $(window).height(); // New height
var width = $(window).width(); // New width
f(previous_height, previous_width, height, width);
previous_height = height;
previous_width = width;
still_running = false;
}, 125);
}
});
}
/* Example of usage. Pass in the function to get executed */
on_resize(
function(ph, pw, h, w) { console.log ("Screen size has changed. New size: " + h + ", " + w); }
);
@perpetual-hydrofoil
Copy link
Author

The whole point of this is that it protects against the resizing process - calling multiple times when it's actually only a single continuous event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment