Search code examples
javascriptjquerykey-valuefor-in-loop

Loop through object key/values correctly for active body class


I'm trying to loop through an object with some data in it, compare the value to the window width, find out which one is essentially 'active' in the range, then use that in the body tag.

var breakpoints = {'size-s': 320, 'size-m': 768, 'size-l': 1024, 'size-xl': 1440},
    activeClass;

$(window).on('resize orientationchange', function () {
    for (var prop in breakpoints) {
        if($(window).width() > breakpoints[prop] && $(window).width() < breakpoints[prop]) {
            activeClass = prop;
        }
    }
});

Examples:

  • If window width = 800 that means that the activeClass should be 'size-m'.
  • If window width = 1023 that means that the activeClass should be 'size-m'.
  • If window width = 1024 that means that the activeClass should be 'size-l'.

Fairly sure this is the direction but don't understand the premise(s) in order to progress. A little help would be great :)

NOTE: Well aware of css media queries - has to be a js solution please :)


Solution

  • The issue was the logic of comparing same property as < and >

    $(window).width() > breakpoints[prop] && $(window).width() < breakpoints[prop]
    

    I have corrected it, also introduced a different logic. Breakpoints can work like this

    var breakpoints = {
     'size-s':  { 'size' : 320, 'next' : 'size-m'},
     'size-m': { 'size' : 768, 'next' : 'size-l'},
     'size-l': { 'size' : 1024, 'next' : 'size-xl'},
     'size-xl': { 'size' : 1440, 'next' : undefined}};
    

    Now each break point has its higher screen size, like a a linked hash map. Watch out for the bottle necks.

    The working fiddle is here https://jsfiddle.net/p7nh7eyn/