Window. MatchMedia method

The window.matchMedia method returns a MediaQueryList object. Window.matchmedia accepts a media query string as an argument.

const mql1 = window.matchMedia('(max-width: 600px)');

const mql2 = window.matchMedia('(min-width: 400px) and (max-width: 800px)');
Copy the code

MediaQueryList object

Attribute matches

Returns a Boolean value. Determines whether the current document matches the media query string. The match returns true. Otherwise return false.

const mql = window.matchMedia('(max-width: 600px)');

mql.matches
Copy the code

Does not match the media query string

Matches the media query string

Properties of media,

Returns the media query string

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');

// "(min-width: 400px) and (max-width: 800px)"
mql.media
Copy the code

Methods addListener

Add a listener to the MediaQueryList object.

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');

const callback = function () {
    if (mql.matches) {
        console.log('match')}else {
        console.log('Mismatch')
    }
}

mql.addListener(callback)
Copy the code

Only if MQL. Callback is called only when matches changes. If you want to execute the logic from the beginning. The callback can be called manually

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');

const callback = function () {
    if (mql.matches) {
        console.log('match')}else {
        console.log('Mismatch')
    }
}

callback()
mql.addListener(callback)
Copy the code

Methods removeListener

Used to remove listeners

const mql = window.matchMedia('(min-width: 400px) and (max-width: 800px)');

const callback = function () {
    if (mql.matches) {
        console.log('match')}else {
        console.log('Mismatch')
    }
}

mql.addListener(callback)
mql.removeListener(callback)
Copy the code

reference

  • Window.matchMedia
  • MediaQueryList