Swapping out a background video for a background image in cases where auto-play is restricted on the device

How can I replace an auto-play background image with a static image on devices that do not support auto-play? The <video> tag's POSTER attribute works, but it seems that on my iPhone (which does not allow auto-play), the video is still downloaded even though it is not used. Is there a more effective solution for this issue?

(The post about autoplay detection partially addresses this question, but my query is slightly different and I have provided a response below.)

#video-bg {
  position: relative;
  width: auto;
  min-width: 100%;
  height: auto;
  background: transparent url(video-bg.jpg) no-repeat;
  background-size: cover;
display: block;
}
video {
  display: block;
}

.video-container {
  width: 100%;
  max-height: 550px;
  overflow: hidden;
  position: static;
  top: 0;
  right: 0;
  z-index: -100;
}
.overlay-desc {
  background: rgba(0,0,0,0);
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
<div id="top-banner-vid" class="container-fluid px-0">
  <div class="row no-gutters video-container">
    <div class="col">
      <video class="embed-responsive video-bg" poster="12-sunrise-picture.jpg" autoplay loop muted>
        <source class="embed-responsive-item" src="http://www.icutpeople.com/wp-content/themes/icutpeople/assets/video/waynesworld.mp4" type="video/mp4">
        Your browser does not support the video tag. Please update your browser to enjoy the full features of this website. </video>
      <div class="container overlay-desc">
        <h1>Wayne's World</h1>
      </div>
    </div>
  </div>
</div>

Answer №1

To begin, ensure that the HTML5 autoplay attribute is supported by following this detection method:

$(function() {
    let $container = $('#top-banner-vid .video-container > .col');
    let $video = $.parseHTML('<video class="embed-responsive video-bg" poster="12-sunrise-picture.jpg" autoplay loop muted><source class="embed-responsive-item" src="http://www.icutpeople.com/wp-content/themes/icutpeople/assets/video/waynesworld.mp4" type="video/mp4">Your browser does not support the video tag. Please update your browser to enjoy the full features of this website.</video>');
    let $image = $.parseHTML('<img src="12-sunrise-picture.jpg"/>');

    function addVideo() {
        $container.append($video);
    }

    function addImage() {
        $container.append($image);
        $image.on('click', () => {
            $container.empty().append($video);
        });
    }

    if (autoplaySupported()) {
        addVideo();
    } else {
        addImage();
    }
}();

Keep in mind that even after it loads, users will have to click it again to play. You may then want to explore initiating the video playback using a click event as well, which can be challenging. Learn more about playing and pausing an HTML5 video with JavaScript here.

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

What is the proper way to convert the Vue3 ::v-deep SASS syntax to utilize :deep?

HTML: <template> <form class="bg-white"> <div class="source-field"> ... The original SASS code looks like this: .form::v-deep .source-field width: 129px display: inline-block margin: 0px 2px 5px 2px ...

AngularJS: How service query data is perceived as an object and therefore cannot be utilized by Angular

When retrieving data from my PHP server page in the factory service, I encountered two different scenarios: If I call a function that returns an array and then use json_encode($data); at the end, Angular throws a resource misconfiguration error due to ...

Achieving the retrieval of all data can be done simply by utilizing the `echo json_encode($data);

I am trying to automatically update the user wall with new data from the database using a script that checks for updates every 15 seconds. Everything works fine when I only use one piece of data like $data = $row['description']; in the server.ph ...

Is there a way to alter the background color of a Material UI card when it is being hovered over

I'm currently using material ui with react and I have a question regarding the background color of my card component when a user hovers over it. Can someone help me figure out how to achieve this? For reference, here is the live code link in CodeSand ...

Maintain a persistent Facebook login session using PHP and Puppeteer

Currently, I am utilizing puphpeteer, a PHP bridge for node's puppeteer that supports the entire API. My task involves scraping various Facebook pages to gather specific information. To accomplish this, I need to login with my credentials and then acc ...

Multiple occurrences of trigger events were detected when loading ajax content

In a div I have embedded a paragraph and a button as shown below: <div id="my_div"> <p>This is a paragraph</p> <button class="my_btn">Click here!</a> </div> The content within the div is dynamically loaded via ...

Exploring the capabilities of a VueJS-compatible product tour library

I am currently working on implementing a feature intro tutorial for my web application, similar to what can be done with intro.js. However, I am encountering an issue where nothing seems to happen when using intro.js - no error messages or tour messages ar ...

Hover over the entire row to see it light up

I am trying to create a JavaScript function that loops through a variable number of iterations and dynamically generates HTML elements on the DOM / Webpage. Once the loop is complete, it populates the following div: <div class="energyRowContainer" id ...

Is there a way to improve the efficiency of this jQuery function that toggles the image source?

I have implemented a functionality that seems to work, but I'm unsure if it's the most efficient solution. I couldn't find a ready-made 'copy-paste' solution online, so I ended up writing this code myself. I am sticking with the &l ...

Automatically log users out of Django and update the backend after a period of inactivity without requiring any additional requests

In my Django project, I am working on a simple multiplayer system where I need to update the isCurrentlyActive value in a user-related model automatically and then log them out. I tried using middleware following a solution from this post, which works well ...

What is the reasoning behind excluding any JavaScript code between the <script> tags when our intention is solely to incorporate an external JS file?

It's puzzling to me why the author of the "Javascript & Jquery: the missing manual , second edition" recommends the following sentence: When including the src attribute to connect to an external JavaScript file, avoid placing any JavaScript cod ...

Building a custom form layout using Bootstrap v4 with three input fields and a button all lined up on one

I am struggling to create a form with 3 input fields and a button on the same row using Bootstrap v4 for the design. Can anyone help me figure this out? Take a look at my current design: Click here My Code <div class="col-sm-7 mx-auto bg-faded"&g ...

Navigation bar subtitle with items aligned to the right

My navigation bar includes a subtitle, and I implemented the technique found here to add it. However, after adding the subtitle, my nav bar lost its right alignment. Some items in the nav bar need to be aligned to the right, but they are no longer since I ...

Verify that the mapDispatchToProps function has been executed

I have been struggling to test the execution of my mapDispatchToProps function with arguments. Despite following guidance from a previous question on Stack Overflow, I still can't seem to make it work. Component.jsx const mapDispatchToProps = dispatc ...

Having trouble getting this JavaScript query to function properly

The initial div in the code snippet below showcases the name of a university. When this name is clicked, it activates the function display_people(). This function is responsible for displaying or hiding the individuals associated with that university. The ...

What is the best way to highlight the active link in my sidebar navigation bar when using material design in an Angular application?

<div class="mt-3"> <mat-nav-list> <a mat-list-item class="ml-2" style="font-size:15px;" (click)='paycard.html'> SERVICES </a> <a mat-list-item class="ml-2" style="font-size:15px;" (click ...

Can the process of rounding values enhance the speed of JSON communication during AJAX requests?

Considering how frequently I need to retrieve large amounts of data multiple times within seconds using the $ajax or jQuery.getJSON method, I am contemplating the idea of rounding long floating-point values (e.g. 1.23242342344...) to shorter versions. My ...

Challenges with resizing windows in jQuery

I'm currently working on optimizing my jQuery code and everything seems to be running smoothly so far: jQuery $(document).ready(function(){ $(".fadeinbg").click(function(){ $("#content").fadeIn(); }); var height = $(window).height() ...

Divide the array of words into segments based on the maximum character limit

I am looking for a way to divide an array of words into chunks based on a maximum number of characters: const maxChar = 50 const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,&apo ...

Only one admin account can be accessed at a time by multiple logins

I am looking to add a new feature to my app where only one admin can log in at a time. If someone else tries to log in with the same admin ID on another device, a warning should be shown, indicating that the user is already logged in and cannot access the ...