Ruxandra Anghel
Ruxandra Anghel

Reputation: 173

Modernizr.mq in vanilla JS

I'm trying to get rid of Modernizr in my project but I can't seem to understand or find a replacement for the .mq function. Can someone explain or provide a bare solution to my problem?

Upvotes: 3

Views: 560

Answers (2)

Patrick
Patrick

Reputation: 13984

Modernizr is open source - you can see exactly what it does here.

In modern browsers, it will almost always just be window.matchMedia

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075925

According to the Modernizr docs, mq checks whether the page current matches a media query you pass it, e.g. if (Modernizr.mq('(min-width: 900px)')) to test if the window is at least 900px wide.

On vaguely-modern browsers (IE10+, details here), you can use window.matchMedia to do that. Example from that page:

if (window.matchMedia("(min-width: 400px)").matches) {
  /* the viewport is at least 400 pixels wide */
} else {
  /* the viewport is less than 400 pixels wide */
}

Upvotes: 5

Related Questions