Learning notes mediaquerylist

Time:2021-10-18

Window.matchmedia method

window.matchMediaMethod returns aMediaQueryListObject.window.matchMediaAccepts the media query string as a parameter.

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

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

Mediaquerylist object

Attribute matches

Returns a Boolean value. Judge whether the current document matches the media query string. Match returns true. Otherwise, false is returned.

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

mql.matches

Learning notes mediaquerylist

Media query string mismatch

Learning notes mediaquerylist

Match media query string

Attribute media

Return media query string

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

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

Method 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)

Only when MQL. Callback is called only when matches changes. If you want to execute logic at the beginning. You can manually call callback again

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)

Method 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)

reference resources