I'm using JavaScript to handle breakpoints in a single page, non-scrollable application. I want to do various things when changing viewports, such as fire off animations with a JavaScript animation library.
I've assigned the viewports like so:
HTML:
<div class='box'></div>
CSS:
.box {
width: 300px;
height: 300px;
background-color: red;
}
JS:
var winWidth = '';
var newWinWidth = '';
var winHeight = '';
var newWinHeight = '';
function setWidthBreakpoints(windowWidth) { //matches bootstrap's breakpoints
if (windowWidth >= 1200) {
newWinWidth = 'lg';
} else if (windowWidth >= 992) {
newWinWidth = 'md';
} else if (windowWidth >= 768) {
newWinWidth = 'sm';
} else {
newWinWidth = 'xs';
}
}
function setHeightBreakpoints(windowHeight) {
if (windowHeight >= 1024) { //more or less arbitrary, may add or remove
newWinHeight = 'lg';
} else if (windowHeight >= 480) {
newWinHeight = 'md';
} else {
newWinHeight = 'sm';
}
}
window.onresize = function () {
'use strict';
setWidthBreakpoints($(this).width());
setHeightBreakpoints($(this).height());
if (newWinWidth !== winWidth || newWinHeight !== winHeight) {
onSizeChange();
winWidth = newWinWidth;
winHeight = newWinHeight;
}
};
function onSizeChange() {
switch(newWinWidth + '|' + newWinHeight) {
case 'xs|sm':
$('.box').css('background-color', 'yellow')
case 'xs|md':
case 'xs|lg':
$('.box').css('background-color', 'purple')
case 'sm|sm':
$('.box').css('background-color', 'orange')
case 'sm|md':
case 'sm|lg':
$('.box').css('background-color', 'purple')
case 'md|sm':
$('.box').css('background-color', 'green')
case 'md|md':
case 'md|lg':
$('.box').css('background-color', 'purple')
case 'lg|sm':
$('.box').css('background-color', 'blue')
case 'lg|md':
case 'lg|lg':
$('.box').css('background-color', 'purple')
}
}
In the above code, we want anything above a small height to be purple. But we have to repeat ourselves to set it four different times.
I will be supporting IE9 with this application so I chose to use JS animation library GSAP for performance and fallback reasons. This is why I am handling my media query breakpoints in Javascript.
How can I build such a scheme to minimize code repetition? Is there a more elegant way to handle combined height and width breakpoints? Am I doing it wrong? I don't foresee many more height viewports being added to this application, and the width ones are tied to Bootstrap so they won't be changing at all.