JavaScriptNo Comments

default thumbnail

It is possible to use media queries using Media Queries using javascript. The key API iswindow.matchMedia()which method returns a new MediaQueryList object that can then be used to determine if the document matches the media query.

const ab = window.matchMedia( "(min-width: 769px)" );

The matches property returns true or false depending on the query result. For example:

if (ab.matches) {
// window width is at least 769px
} else {
// window width is less than 769px
}

You can also add an event listener which fires when a change is detected:

// media query event handler
if (matchMedia) {
const ab = window.matchMedia("(min-width: 769px)");
ab.addListener(WidthChange);
WidthChange(ab);
}

// media query change
function WidthChange(ab) {
if (ab.matches) {
// window width is at least 769px
} else {
// window width is less than 769px
}
}

Be the first to post a comment.

Add a comment