Ben Carey
Ben Carey

Reputation: 16968

Match most relevant media query in Javascript

Consider the following array:

const mediaQueries = [
    '(max-width: 730px)',
    '(max-width: 1600px)',
    '(min-width: 1600px)'
];

And now consider the following loop:

mediaQueries.forEach(query => {

    let mql = window.matchMedia(query);

    if (mql.matches) {
        console.log('match: ' + query);
    }

});

The above code will loop through each of the media queries and log if they match based on the current screen size.

The Problem

On a screen that is 700px wide, both the (max-width: 730px) and the (max-width: 1600px) will match.

I need to somehow return only the most revelant match based on query size, and query type. Using the 700px screen as an example, this should only return (max-width: 730px).

Is there a way to achieve this with window.matchMedia or is the simplest way to just apply a custom order to the array based on the value of the query and type of query, and then return the first match?

Upvotes: 0

Views: 479

Answers (1)

baao
baao

Reputation: 73251

If your array holds the values in the correct order, the simplest is to use find()

const matchingQuery = mediaQueries.find(query => 
    window.matchMedia(query).matches
);

Upvotes: 2

Related Questions