2

Thanks to this answer, I use video[poster]{object-fit:fill} in my css to avoid distorted poster images in html5 videos. Since poster seems stylable, I also want to use css to display different posters for a video, depending on screensize (mobile or desktop). But video[poster]{background-image:url(poster.jpg) doesn't produce any result, presumably poster is not a background. So I tried adapting some javascript found here, as follows:

function myFunction(x) {
  if (x.matches) { // If media query matches
    document.getElementById("video").poster = "poster1.jpg";
  } else {
    document.getElementById("video").poster = "poster2.jpg";
  }
}
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction)

It doesn't work either, but maybe it's just missing some little thing (even the original fails javascript validation) Anybody know how to apply media queries to the poster property?

plugincontainer
  • 630
  • 2
  • 9
  • 28
  • The other solution in the quoted answer - use transparent gif as poster, and then media queries for background-image to video - fails in IE-11 (no poster appears) – plugincontainer Feb 12 '19 at 04:41

1 Answers1

1

Remove the x in myFunction(x).

The API has changed and now it will be an Event that you'll receive here, while in previous implementations it was indeed the MediaQueryList.

Just keep the out reference to your MediaQueryList and you should be fine.

function myFunction(evt) {
  console.log(evt && evt.toString());
  if (x.matches) { // If media query matches
    document.getElementById("video").poster = "https://lorempixel.com/200/400";
  } else {
    document.getElementById("video").poster = "https://lorempixel.com/400/200";
  }
}
var x = window.matchMedia("(max-width: 500px)")
myFunction() // Call listener function at run time
x.addListener(myFunction)
.as-console-wrapper{max-height:20px!important}
<video id="video" controls></video>
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • Thanks! One question... what's .as-console-wrapper{max-height:20px!important} ?? It's not in the code anywhere else or in my videojs player css. Just curious. – plugincontainer Feb 12 '19 at 08:40
  • That's CSS for StackSnippet's console, otherwise it would have taken the whole snippet. Simply ignore it. – Kaiido Feb 12 '19 at 08:49