Tips for implementing CSS media queries on video posters

After implementing the solution from this helpful answer, I have successfully used video[poster]{object-fit:fill} in my css to prevent distorted poster images in html5 videos. Now, I am looking to use CSS to display different posters for a video based on screen size (mobile or desktop). However, trying

video[poster]{background-image:url(poster.jpg)
did not yield any results, indicating that poster may not be a background property. To address this issue, I attempted to modify javascript code found here:

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)

Unfortunately, this approach did not work as expected. It is possible that there is a small detail missing (even the original failed javascript validation). Does anyone know how to effectively apply media queries to the poster property?

Answer №1

Eliminate the x from myFunction(x).

The API has been updated, and now you will be receiving an Event here instead of the MediaQueryList used in previous versions.

Simply retain the reference to your MediaQueryList and everything should work correctly.

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS: Enhancing User Input Experience with Bidirectional Data Binding for Numeric Inputs

I'm exploring the use of Angular for data-binding with input type="number" elements, but I'm encountering difficulties in getting the binding to work. When I make changes to any value, I expect the corresponding binded value to update as well. J ...

What is the best way to tailor a SELECT statement option to reveal a specific div on a different webpage?

Whenever I click on a drop-down list, it redirects me to the same page. What I actually want is for each drop-down option to lead to different pages within my project. Can someone please assist me with this? Below is the PHP code snippet responsible for h ...

Tips for effectively nesting HTML Custom Elements visually

I'm currently working on developing a basic HTML Custom Element for incorporating trees into web pages. The code structure I'm using is quite simple, as shown below: <html-tree title="root"> <tree-node title="child1" ...

Implementing Bottleneck to control the rate of API requests within a software tool

In TypeScript, I am developing an API wrapper with asynchronous code to abide by the rate limit of 1 request/second set by the particular API. My goal is to create a single instantiated API wrapper that enables access to different endpoints using objects. ...

Is the size of the node_modules directory a factor in the cold start performance of cloud functions?

In my understanding, it is best practice to only import necessary modules in the global scope of the index file to minimize cold start times. However, I am still unsure whether the size of the node_modules folder (or the number of dependencies listed in t ...

What is the best way to create a tooltip that appears when a user hovers over text within an <ins> tag?

Alright, I've defined a custom <ins> tag with the following CSS: ins{ color:blue; font-weight:500; text-decoration:none; } ins:hover{ cursor: pointer; cursor: hand; text-decoration:underline; } I'd like to add a ...

Communication with child processes in node.js is not done using the child_process module

Hello Everyone, I'm currently experimenting with node.js to utilize JS plugins developed by others using the child_process API. However, I'm facing an issue where the child process is not able to communicate effectively with the parent process. ...

"Vanishing Act: Google Maps Markers in React Mysteriously Disappear upon

Struggling with the react-google-maps module, particularly when it comes to markers and component re-rendering. Here's the issue: Initially load page with map and a few markers (all good) Click on a tab in the nav-bar -> page switches content in ...

jQuery's element loading function fails to work with ajax requests

When trying to preload ajax data before attaching it to a div, I utilized the following code: $.ajax({ url: 'ajax.php', data: { modelID:id }, type: 'post', success: function(result){ $(result).load(function(){ ...

Easily collect form information from an HTML <form> element

I've been struggling to figure out how to retrieve data from an HTML form and display it in the console. What step am I overlooking? Here is the HTML code I'm working with: <!DOCTYPE html> <html> <head> <title>U ...

Enhance your pandas to_html experience by including custom attributes to the table tag

Currently, I am utilizing the pandas to_html() function to construct a table for my website. My goal is to include additional attributes to the <table> tag, but I am unsure of the process. my_table = Markup(df.to_html(classes="table")) This code sn ...

Steps to trigger the "Confirm form resubmission" prompt when a user attempts to refresh their browser

I am encountering a situation where users are unable to refresh the page by clicking the browser's refresh button or pressing F5. I would like to simulate 'form resubmission' in order to display a prompt message. Could someone please provid ...

What could be causing the malfunction of removeEventListener in my Nuxt application?

Whenever a search result is displayed on my app, the component below renders and checks if the user scrolling is at the bottom of the page. Initially, the code works fine, but I encounter an error when returning to the page after navigating away and scro ...

Increasing numerical section of text with JavaScript

Is there a way to increment the numeric part at the end of a string in JavaScript when certain actions occur? For example: var myString = 'AA11111' increaseStringValue(myString) # Updated value of myString => 'AA11112' Additional ...

Adjust the path-clip to properly fill the SVG

Is there a way to adjust the clip-path registration so that the line fills correctly along its path instead of top to bottom? Refer to the screenshots for an example. You can view the entire SVG and see how the animation works on codepen, where it is contr ...

retrieve information from MySQL database for application in JavaScript

My current project involves a JavaScript that dynamically constructs an HTML page, complete with textarea boxes for users to input information. This data is already stored in a MySQL database, and I am looking for a way to populate these textarea boxes w ...

Integrate a PHP form that includes a redirect feature and an optional opt-in box

I'm a beginner and I'm trying to enhance this code by adding some extra features. When the form is submitted, I want the page to redirect to an external URL like www.google.com The checkbox should be automatically checked and when the client re ...

Not every situation calls for the same type of styling

I am struggling to override the CSS for <h1> and <h2> using specific selectors only. The changes are only being applied to one class, with <h1> changing color to green but not <h2>. Can someone please assist me in identifying where ...

Error: The object prototype can only be an Object or null, not undefined

During development, my app runs smoothly. However, when I build the project for production using "npm run build," I encounter the following error: 2.9b72e8af.chunk.js:sourcemap:1 Uncaught TypeError: Object prototype may only be an Object or null: undefin ...

Tips for Positioning Javascript Onclick at the Center of the Screen

Could someone please assist me with centering my JavaScript pop up on the screen? Currently, when I scroll down and activate the onclick popup, it appears at the top of the page, out of view. How can I ensure that the popup appears in the center of the scr ...