Search code examples
javascriptjqueryobject-literal

JavaScript Object Literal and jQuery $(classes)


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)


Solution

  • 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.

    // create a variable to store the only class you want to apply
    var apply = "";
    for (var key in breakpoints) {
        // keep overwriting the apply var if the new key is applicable
        if (winWidth >= breakpoints[key]) {
           apply = key;
        }
        // remove any existing classes with that keyname
        $('body').removeClass(key);
    }
    // add the key to the body as a class
    $('body').addClass(apply);
    

    Also, you can remove breakpoints.hasOwnProperty(key) as the for-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:

    var apply = "";
    var check = 0;
    for (var key in breakpoints) {
        // Also check if the value is higher than the last set value
        if (winWidth >= breakpoints[key] && breakpoints[key] >= check) {
            apply = key;
            check = breakpoints[key];
        }
        $('body').removeClass(key);
    }
    $('body').addClass(apply);