12

I'm using window.matchMedia conditional in order to avoid the inject of a video in mobile devices. CanIUse reports that matchMedia is going to work smoothly since Safari 9 (I'm testing on it), but my code is completely ignored:

if ( window.matchMedia("(min-width: 1025px").matches) {
   console.log('match');

   document.addEventListener("DOMContentLoaded", function() { initialiseMediaPlayer(); }, false);

   function initialiseMediaPlayer() {

      (stuff here...)

   }

}

This code works perfectly on Chrome, Chromium, Firefox, IE and Edge.

Does anyone had a similar issue?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Marco
  • 712
  • 1
  • 10
  • 23

4 Answers4

18

The issue is in the formatting, oddly enough the other browsers fix the behavior even though it is malformed. It's missing an additional closing ")" parenthesis after the 1025px. Try:

if ( window.matchMedia('(min-width:1025px)').matches) {
   console.log('match');

   document.addEventListener("DOMContentLoaded", function() { initialiseMediaPlayer(); }, false);

   function initialiseMediaPlayer() {

      (stuff here...)

   }

}
Zanderi
  • 907
  • 9
  • 15
  • No worries it's good to know that other browsers fix it and safari does not :) – Zanderi Mar 24 '16 at 19:27
  • That's true! I spent almost one week without noticing that missing bracket! But I develop on chrome and Firefox, and that bracket was almost invisible to me, why on earth does it work on all environment not in safari ;) ahahahh nice catch!!! – Marco Mar 25 '16 at 02:46
  • This helped me find my issue too. Except my testers were using Chrome on an IPhone. Strange indeed. – JGTaylor Jun 08 '18 at 21:26
10

For anyone else who may come across similar issues, I found that in safari you need to include 'screen and' as well as the width setting. Other browsers seem to assume that you are talking about the screen width but safari needs it specified, at least in my case. so would be something like:

if ( window.matchMedia('screen and (min-width:1025px)').matches) {}

in this case

mix3d
  • 4,122
  • 2
  • 25
  • 47
Richard Harris
  • 311
  • 1
  • 3
  • 12
4

In my case, it was that Safari uses .addListener() instead of addEventListener() on the mediaQueryList.

docta_faustus
  • 2,383
  • 4
  • 30
  • 47
4

If someone stumbles across this too, in my case the problem was, that safari doesn't have the .onchange property on the MediaQueryList interface. This was just resolved in Safari 14, but the release is rather new, so use (the deprecated) .addListener if you want to ensure backwards compatibility.

Source: https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/onchange

Mayor Mayer
  • 150
  • 2
  • 12