Sophisticated solution for html5 video fallback with JavaScript

My Django website allows users to upload videos in mp4 format for others to watch. However, there are cases where certain browsers cannot play this format, like Firefox. In such scenarios, I want to provide a fallback option to download the video instead of streaming it.

I attempted to implement a fallback solution following a sample code, but I'm facing issues with it in my Django template. Could someone help me troubleshoot this problem? Any assistance would be greatly appreciated.

{% extends "base.html" %}
{% block content %}
<div class="margin">
<table>

    {% for video in object_list %}

    <tr><td>
    <a name="section{{ forloop.counter }}"></a>

    <a href="{% url 'videocomment_pk' video.id %}">
    {{ video.caption }}
    <button>
    Comment
    </button>           
    </a>

    <br>
        <video width="500" height="350" controls autoplay>
        <source src="{{ video.url }}" type='video/mp4; codecs="mp4v.20.8, samr"'>
            <a href="{{ video.url }}">
                <img src="xyz.jpg" title="Your browser does not support the <video> tag">
             </a>
        <p>Your browser does not support the <video> tag</p>
        </video>


        <br>

    </td></tr>

    {% endfor %}
    </table>
<script>
var v = document.querySelector('video'),
    sources = v.querySelectorAll('source'),
    lastsource = sources[sources.length-1];
lastsource.addEventListener('error', function(ev) {
  var d = document.createElement('div');
  d.innerHTML = v.innerHTML;
  v.parentNode.replaceChild(d, v);
}, false);
    </script>

</div>
<br>
{% endblock %}

{% block pagination %}
{% if is_paginated %}
<div class="pagination">
    {% if page_obj.has_previous %}
    &nbsp;&nbsp;&nbsp;<a href="?page={{ page_obj.previous_page_number }}#section0"><button>back</button></a>
    {% endif %}

    {% if page_obj.has_next %}
    <a href="?page={{ page_obj.next_page_number }}#section0"><button >forward</button></a>
    {% endif %}
</div><br>
{% endif %}
{% endblock %}

Answer №1

It appears that one issue could be the presence of multiple video elements on the page, while the JavaScript code copied from the example only targets the first video element.

To address this, you can utilize

document.querySelectorAll('video')
to select all video elements and then loop through each one individually.

UPDATE - Below is a rough snippet of code that could potentially resolve the issue:

var videos = document.querySelectorAll('video');
for (var i = 0; i < videos.length; i++) {
    var v = videos[i];
    var sources = v.querySelectorAll('source'),
        lastsource = sources[sources.length-1];
    lastsource.addEventListener('error', function(ev) {
        var d = document.createElement('div');
        d.innerHTML = v.innerHTML;
        v.parentNode.replaceChild(d, v);
    }, false);  
}

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

Python on the server side generating a downloadable zip file

After passing a parameter from my client to a python script on the server through a GET request, the script initiates a process that results in the creation of a zip file. However, upon making an AJAX call in my client-side JavaScript, I am only able to co ...

Determining if data from two separate lists in Vue.js matches in order to display in the template

I need to compare two sets of data - one fetched from the server and the other being default data. Data retrieved from the server: [ { "id": 7, "day": "14 April 2017", "time_list": [ { "id": 25, "time": "11:00 AM", ...

ng-if directive in AngularJs will not function properly if the condition text includes a space

I encountered an issue while attempting to set values in AngularJS UI grid based on the row.entity values. To address this, I created a cellTemplate that evaluates the row values and applies text styling accordingly. Code Snippet var statusTemplate=&apos ...

Looking to add some color to the tags within an XML document that is being shown in a textarea?

Currently, I am attempting to add color to the tags within an XML string that is being displayed in a textarea on an HTML page. For example, let's say I have an XML string stored in a variable called 'xmldata'. The HTML textarea tag looks ...

Transfer data via ajax to the controller

I need assistance with storing a file in my database using Tabulator without having a form already created. I am currently creating a simple input element like this: var editor = document.createElement("input");. After clicking the file, it trigg ...

Tips for assigning focus properties inside VueJS components

Within my component child Input: <template> <div class="basic-input-outer" :style="styles"> <p class="paragraph-small">{{ title }}</p> <input ref="name" :type="type" cla ...

The getElementByID function will return null in this instance, as it has not been loaded

Hello everyone, I am facing an issue while trying to access an element by its ID in JavaScript as it keeps returning null. This problem arises because the element is not fully loaded when the DOM is initially created, due to a plugin called Restrict Conte ...

invoke scrollToPosition function in React Native

I am trying to execute a function once the scrolling momentum is finished in my react native SectionList. After going through the documentation, I discovered onMomentumScrollEnd. However, the problem is that onMomentumScrollEnd only works when we manually ...

Combine es6 imports from the identical module using an Eslint rule or plugin

Looking to consolidate my ES6 imports from a single module into one for my React project. For example: import { Title } from "@mantine/core"; import { Center } from "@mantine/core"; import { Divider } from "@mantine/core"; T ...

Manually adjust rotation in Three.js by clicking

I am looking to initiate an animated rotation of an object by clicking a button. I have a basic understanding that the render function operates as an infinite loop and that adding 0.1 to cylinder.rotation.x continuously rotates the object. My goal is to ...

The problem of a static click function not working when clicked on a link. What is the solution for this

Details I am currently using a flickity slideshow that automatically goes to the next picture on a click. Within the slideshow, I have placed a button with text and a link to an external website (e.g. ). My Problem: When I click on the link, my slidesho ...

Error: Django's BaseSerializer.save() method was provided with 2 arguments instead of the expected 1

Encountered an issue while setting up the signup feature. When making a GET request, the field values display correctly. However, when sending a POST request, the error below occurs. [ BaseSerializer.save() takes 1 positional argument but 2 were given ] ...

Refreshing ng-repeat dynamically with $http without reloading the page

Just a quick heads-up, I'm new to AngularJS In my AngularJS application, I am using the $http service to fetch data. Each row has an update button that needs to trigger a server-side method (the API is already returning data) to sync with a third-par ...

How to align the navbar toggle button and list items to the right in Bootstrap 5

I'm struggling with a simple html page that has a fixed navbar at the top. Everything looks great when viewed in full-screen mode, with centered links. However, when the page size is reduced, it collapses to a toggle button on the left side. What I re ...

Update the image with a new one using jQuery and PHP, then refresh the page to see

I'm currently utilizing simpleImage, a PHP image manipulation library. My aim is to externally rotate an image using AJAX and replaceWith functions. It successfully replaces the image, but unfortunately it doesn't refresh after rotation. Here&ap ...

How to Create Smooth Transitions for Text Arrays using jQuery's Fade In and Fade Out Features

I need to loop through an array of text and apply jQuery's fadeIn and fadeOut functions to each element. var greetings = ["hi, I'm", "bonjour, je m'appelle", "hallo, ich heiße"] The HTML structure I want is as follows: <h2><span ...

the process of altering properties in vue js

After running my Vue file, I encountered the following console error. As someone new to Vue programming, I'm attempting to utilize a Syncfusion UI component to display a grid. Prop being mutated: "hierarchyPrintMode" I am unsure where to add the comp ...

Performing database queries with MySQL or its equivalent in a Django application

Greetings, I'm facing a challenge with translating a simple MySQL query into Django: SELECT year, month, AVG(mean_air_temp), AVG(min_air_temp), AVG(max_air_temp) from climate WHERE recorded_on >= '1978-09-09' AND recorded_on <= ' ...

The EJS file is failing to display the stylesheet even though it is being pulled from the

Encountering a strange issue where the page routed to display additional information about a specific record from my database list on the homepage is not loading the stylesheets located in my partial/head, despite successfully passing the object informatio ...

Resize an image to fit perfectly within a material-ui grid

Is there a way to resize images within a grid layout without them getting cropped? Each image I try to fit into the top horizontal grid behaves differently due to varying dimensions. Instead of stretching and fitting into the container, the images end up b ...