Skip to content

Instantly share code, notes, and snippets.

@NXTaar
Last active November 9, 2015 00:22
Show Gist options
  • Save NXTaar/84e606bb82e38bbd91a3 to your computer and use it in GitHub Desktop.
Save NXTaar/84e606bb82e38bbd91a3 to your computer and use it in GitHub Desktop.
This snippet is allowing to trigger some functions when browser window size changes (you know, like CSS media queries, changes only when it passes through milestone)
// Created by Valeriy Sagatovskiy
// Create the new instance of changeWithSize with parameters :
// - unit: milestone in pixels causing callbacks, f.e. "1024"
// - dimension: which dimension is watched for changes - "width" or "height"
// - b_callback: will be called if dimension changes from big to small
// - a_callback: will be called if dimension changes from small to big
// If you pass only one callback, it will be called in both directions
// If you don't want any actions on the certain direction, just pass 'null' instead of callback
var changeWithSize = function(unit, dimension, b_callback, a_callback) {
var trigger = undefined;
var size = undefined;
unit = parseFloat(unit);
if (a_callback === undefined) {
a_callback = b_callback;
}
if (a_callback === null) {
a_callback = function() {};
}
if (b_callback === null) {
b_callback = function() {};
}
checkDimension();
if (size() >= unit) {
trigger = true; // за точкой изменения
} else trigger = false; // перед точкой изменения
window.addEventListener('resize', function() {
var _size = size();
if (_size >= unit) {
if (trigger !== true) {
a_callback();
trigger = true;
}
}
if (_size < unit) {
if (trigger !== false) {
b_callback();
trigger = false;
}
}
})
function checkDimension() {
if (dimension !== undefined && dimension !== null && dimension !== "") {
if (dimension === "width") {
return size = function() {
return document.body.clientWidth;
};
}
if (dimension === "height") {
return size = function() {
return document.body.clientHeight;
}
} else return console.error("ChangeWithSize: no dimension parameter!");
} else return console.error("ChangeWithSize: no dimension parameter!");
}
}
// license - MIT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment