lukemcd
lukemcd

Reputation: 1501

Getting a named breakpoint from the browser width and breakpoint object (JavaScript)

I am importing my breakpoint module CSS into JavaScript and am getting an object like this:

const breakpoints = {
  large: "992px",
  medium: "768px",
  small: "500px",
  tiny: "320px",
  xlarge: "1384px"
}

From window.innerWidth I am able to get an integer value of the current browser window width. I would like to use a function that tells the named breakpoint from the window width. For example, a value of 640 would return medium.

The logic is hurting my brain. How can I do it?

Upvotes: 0

Views: 577

Answers (3)

Dan Mullin
Dan Mullin

Reputation: 4415

Here's a simple example of how this could be done. Not dynamic like the other answers, but it doesn't need to be complex considering the small number of properties we're talking about here.

const breakpoints = {
  xlarge: "1384px",
  large:   "992px",
  medium:  "768px",
  small:   "500px",
  tiny:    "320px"
}

function getBreakpoint() {
  return matchMedia(`(min-width: ${breakpoints.xlarge})`).matches ? "xlarge" :
         matchMedia(`(min-width: ${breakpoints.large})`).matches ? "large" :
         matchMedia(`(min-width: ${breakpoints.medium})`).matches ? "medium" :
         matchMedia(`(min-width: ${breakpoints.small})`).matches ? "small" :
         matchMedia(`(min-width: ${breakpoints.tiny})`).matches ? "tiny" : "not found"
}

console.log(getBreakpoint())

Upvotes: 0

Rodericus Ifo Krista
Rodericus Ifo Krista

Reputation: 94

Maybe You can take a look at this code

const breakpoints = {
  xlarge: [993, 1284],
  large: [769, 992],
  medium: [501, 768],
  small: [321, 500],
  tiny: [0, 320],
};

function checkBreakpoint(numBreakpoint) {
  for (key in breakpoints) {
    if (numBreakpoint >= breakpoints[key][0] && numBreakpoint <= breakpoints[key][1]) {
      return key
    }
  }
}

console.log(checkBreakpoint(1000))

You can consider to specify (min width and max width) on each your breakpoints object's property, it will make you easier to define the breakpoint's name, I hope this will help you, thank you

Upvotes: 0

Dave Anderson
Dave Anderson

Reputation: 12314

You need to sort your set of values by the integer values and then filter those for values too small and take the first that is big enough.

Object.keys(breakpoints)
      .sort((a,b) => parseInt(breakpoints[a], 10) - parseInt(breakpoints[b], 10))
      .filter((s) => { return parseInt(breakpoints[s], 10) > 640 })[0]

Upvotes: 1

Related Questions