Skip to content

Commit ec3c787

Browse files
committed
Add a JS util function to return a breakpoint value based on a CSS variable
1 parent 34dad51 commit ec3c787

3 files changed

Lines changed: 28 additions & 0 deletions

File tree

src/js/utils/getBreakpoint.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
/**
2+
* Get the breakpoint value from a CSS custom property.
3+
*
4+
* @param {string} breakpointVar CSS custom property name for the breakpoint.
5+
* @return {string} The breakpoint value.
6+
* @example getBreakpoint('--breakpoint-mobile-to-desktop-nav') => '1200'
7+
*/
8+
export default function getBreakpoint(breakpointVar = '--breakpoint-mobile-to-desktop-nav') {
9+
return getComputedStyle(document.documentElement).getPropertyValue(breakpointVar).trim()
10+
}

src/js/utils/isMobileNav.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import getBreakpoint from './getBreakpoint'
2+
3+
/**
4+
* Check if the current viewport is mobile based on a CSS breakpoint.
5+
*
6+
* @param {string} breakpointVar CSS custom property name for the breakpoint.
7+
* @return {boolean} True if viewport is mobile, false otherwise.
8+
* @example isMobileNav() => true; !isMobileNav() => false
9+
*/
10+
export default function isMobileNav(breakpointVar = '--breakpoint-mobile-to-desktop-nav') {
11+
const breakpoint = parseInt(getBreakpoint(breakpointVar), 10)
12+
return window.matchMedia(`(max-width: ${breakpoint - 1}px)`).matches
13+
}

src/scss/03-base/_variables-css.scss

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@
55

66
:root {
77
/*
8+
* Breakpoints
9+
*/
10+
--breakpoint-mobile-to-desktop-nav: #{map-get($breakpoints, mobile-to-desktop-nav)}; // Used by JavaScript
11+
12+
/*
813
* Heading
914
*/
1015
// Font size

0 commit comments

Comments
 (0)