Hi I have some very basic html for a video:
Here is an example of a video that will cover the whole window and autoplay, on a loop. It's created on demand via JavaScript.
I needed this for a video that should only load and play when requested, i.e. not on every load of the page. (Hiding the element with display: none;
won't do, because the video then still loads even if not displayed.)
/**
* Create the video.
*
* An alternative might have been to use an HTML template tag inside the Twig template,
* to then create an element and append it. But this worked only in Chrome:
* - in Firefox, `autoplay loop muted` (inside the <template>) get converted to
* `autoplay="" loop="" muted=""` (in the Inspector) and there's no playback.
* - in Safari, nothing happens.
*
* Another alternative (that worked this one) is to just append the whole HTML as a
* single string, but it's harder to read.
*/
var video = $('<video />', {
id: 'video',
class: 'myclass',
poster: 'https://path/to/my/poster.jpg'
}).prop({
muted: true,
autoplay: true,
loop: true,
});
var src1 = $('<source />', {
type: 'video/webm', // for Firefox, Chrome; slightly smaller file size
src: 'https://path/to/my/video.webm'
}).appendTo(video);
var src2 = $('<source />', {
type: 'video/mp4', // for Safari, Firefox, Chrome
src: 'https://path/to/my/video.mp4'
}).appendTo(video);
video.appendTo($('body'));
Note that:
muted
, autoplay
, loop
must go inside of prop()
. Setting them as attributes will not work! (And will be quite misleading, because you'd think you set them when in fact you really haven't.)muted
is needed in Chrome for autoplay
to work.Snapshot
, converted the resulting PNG to JPG.The hard-to-read-alternative mentioned above:
$('body').append('<video class="c-congrats c-congrats--outofnew" autoplay loop muted> <source src="https://path/to/my/video.webm" type="video/webm" /> <source src="https://path/to/my/video.mp4" type="video/mp4" /> Your browser does not support the video tag. </video>')
.myclass {
position: fixed;
z-index: -1;
height: 100vh;
top: 0;
left: 0;
}
Please check this simple step, This works well for me
$('video').trigger('play');
Thanks
You can use:
$("#video_player")[0].play();
Or:
$("#video_player")[0].autoplay = true;
Or:
document.getElementById("video_player").setAttribute('autoplay', true);
Whatever suits you. Using $('#video_player').play();
you are referencing to non-existing method play
in jQuery and you should reference to the object found by $("#video_player")
.
To change the src of the video in JS, you just simply need something like that:
function playFile() {
var video = $("#video_player");
video[0].src = "http://www.yoursrc.com/video_new.mp4";
video[0].load();
video[0].play();
};
muted
property if you want to use the autoplay
attribute. Refer to : https://developers.google.com/web/updates/2017/09/autoplay-policy-changes