I have an object that contains a list of browser widths
breakpoints {
smallMobile: 0,
mobile: 480,
tablet: 672,
desktop: 868,
largeDesktop: 1050
}
I want to add a class to the body
of the document based on whether the browser width falls between two values in the breakpoints object.
What I have so far
var key;
for (key in breakpoints) {
if (breakpoints.hasOwnProperty(key))
if (winWidth >= breakpoints[key]) {
$('body').removeClass().addClass(key);
} else {
$('body').removeClass(key);
}
}
}
Now this works, however it also removes ALL classes from the body
. Instead I would like to add only one class, and not have to remove anything unless the breakpoint no longer matches.
I'm sure there has to be a way. Any help would be appreciated :)
EDIT
Current output at various widths
>= 1050: <body class="smallMobile mobile tablet desktop largeDesktop">
>= 868: <body class="smallMobile mobile tablet desktop">
>= 672: <body class="smallMobile mobile tablet">
Ideal output
>= 1050: <body class="largeDesktop">
>= 868: <body class="desktop">
>= 672: <body class="tablet">
(For the record I use Media Queries, but I need access to classnames for an edge case)
I've slightly modified your code and saved the class thats the highest applicable one. Then I remove every class and apply the applicable one.
Also, you can remove
breakpoints.hasOwnProperty(key)
as thefor
-loop only loops through keys that actually exist anyway, so you are doing an unnecessary check.Update
At @juvian's note, I'll add a way to make sure that the order in which you make your object makes no difference: