I'm testing on building a site locally on my machine using bootstrap.
I have a <video> sort of as the header of the site.
I would like this video to show the full width and height on mobile, and show a cropped/wide version of the video on desktop. I tried using inline media queries in the <source> tags, so that the src would change but nothing would work.
So I switched gears and used some javascript to change it that way.
So the crazy thing is, it seems my script works. When I look in chrome dev tools, the srcdoes in fact change when I resize my browser screen, however, it does not reflect on the site itself, it keeps whatever src I set it to in the html, as if it is ignoring my script.
I have tried everything I could think of, and I'm just stuck, not sure how to go about it any further. My code is below:
HTML
<video class="col-12" loop muted autoplay >
<source id="hvid" src="media/test.mp4" type="video/mp4">
</video>
JS
let homeVideo = document.getElementById('hvid')
console.log(homeVideo.src)
function myFunction(x) {
if (x.matches) { // If media query matches
homeVideo.src = "media/test.mp4";
} else {
homeVideo.src = "media/test-3.mp4";
}
}
var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes
;
console.log(homeVideo.src)
-Edits-
JS
var w = window.matchMedia("(max-width: 700px)");
var vid = document.getElementById("vid");
var source = document.getElementById("hvid");
window.addEventListener("resize", function screenres(){
if (w.matches) {
vid.pause();
source.src = "media/test.mp4";
vid.load();
vid.play();
} else {
vid.pause();
source.src = "media/test-3.mp4";
vid.load();
vid.play();
};
});
HTML
<div class="container">
<div class="row">
<video id="vid" class="col-12" loop muted autoplay>
<source id="hvid" src="media/test.mp4" type="video/mp4">
</video>
</div>
</div>
Just get the viewport size, and based on that value, pause the video, change the src link, load the new video and play the new video.
But do note that you will need to refresh the page after changing the browser size to see the video change.
If you want the video to change whenever the screen resizes as well as on page refresh, you will first need to move the above JavaScript to a function and run it when a resize event is fired. Then, for the page load, you need to remove the video element from your HTML and add it on page load using the createElement() method with the src attribute value also added depending on the viewport width.
Check this JSFiddle or run the following Code Snippet for a practical example of what I have described above:
/* JavaScript */
var w = window.matchMedia("(max-width: 700px)");
var vid = document.getElementById("vid");
var source = document.createElement("source");
source.id = "hvid";
source.setAttribute("type", "video/mp4");
vid.appendChild(source);
if (w.matches) {
vid.pause();
source.removeAttribute("src");
source.setAttribute("src", "https://storage.googleapis.com/coverr-main/mp4/Love-Boat.mp4");
vid.load();
vid.play();
} else {
vid.pause();
source.removeAttribute("src");
source.setAttribute("src", "https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4");
vid.load();
vid.play();
}
window.addEventListener("resize", function(){
var w = window.matchMedia("(max-width: 700px)");
var vid = document.getElementById("vid");
var source = document.getElementById("hvid");
if (w.matches) {
vid.pause();
source.src = "https://storage.googleapis.com/coverr-main/mp4/Love-Boat.mp4";
vid.load();
vid.play();
} else {
vid.pause();
source.src = "https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4";
vid.load();
vid.play();
}
});
/* CSS */
html, body {margin: 0; padding:0; width: 100%; height: 100%;}.row{display: block !important;}
<!-- CDN Links -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/><link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<!-- HTML -->
<div class="container">
<div class="row">
<video id="vid" class="col-12" loop muted autoplay></video>
</div>
</div>
Related
I am trying to create an HTML video playlist and currently I am using vid.onended to detect when a video is done playing (based of the current video src) and then play the next video when the video ends. This works perfectly for the first video but for some reason it never plays the second video and jumps straight to the third video.
My code:
//add video playlist functionality to auto play next video based on id
var vid = document.getElementById("urlVideo");
vid.onended = function() {
var video0 = "http://techslides.com/demos/sample-videos/small.mp4";
var video1 = "https://media.w3.org/2010/05/sintel/trailer.mp4";
var video2 = "http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
if (vid.src = video0) {
vid.src = video1;
}
if (vid.src = video1) {
vid.src = video2;
}
};
<video id="urlVideo" width="100%" height="460" controls autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
What am I doing wrong?
Edit:
Answer by Alen Toma works perfectly.
I Also managed to do it according to the current video source based on a comment by Quentin, For anyone else looking for how to do it explicitly with the current video source as the variable/condition, please see
https://jsfiddle.net/redlaw/qjb5h7e9/9/
I did make a small example below, it should help.
Have a look at this JSFiddle.
//add video playlist functionality to auto play next video based on id
var videoSrc = [
"https://media.w3.org/2010/05/sintel/trailer.mp4",
"http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"
]
var vid = document.getElementById("urlVideo");
var index = 0;
vid.addEventListener("ended", function() {
var currentSrc = videoSrc[index];
index += 1;
if (index >= videoSrc.length)
index = 0; // Make Loop and jump to the first video
vid.src = currentSrc;
vid.play();
console.log(currentSrc)
}, true);
<video id="urlVideo" controls autoplay>
<source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
</video>
you must use an event listener for your video player like this code:
var vid = document.getElementById("urlVideo");
vid.addEventListener("ended", function() { /* your code*/ }, true);
Everything in my code works. It just doesn't switch to the next song/video after finishing the current one. I have tried adding an onended event handler (in the tag and in JavaScript) but failed. I also tried jQuery but it did't work. For some reasons it doesn't change songs at the end of the song. Instead, it will replay the same song over and over again.
<video id="vid" src="main/" playsinline autoplay loop>
<script>
var video = document.currentScript.parentElement;
video.volume = 0.1;
var lastSong = null;
var selection = null;
var playlist = ["main/songn.mp4", "main/songl.mp4", "/main/songt.mp4", "/main/songf.mp4"]; // List of Songs
var video = document.getElementById("vid");
video.autoplay=true;
video.addEventListener("ended", selectRandom);
function selectRandom(){
while(selection == lastSong){
selection = Math.floor(Math.random() * playlist.length);
}
lastSong = selection;
video.src = playlist[selection];
}
selectRandom();
video.play();
</script>
</video>
You just need to remove the loop parameter from the video tag if you want to trigger the end event (doc):
<video id="vid" src="main/" playsinline autoplay>
(Your code will handle the loop by loading a new song when one ended.)
BTW, keep var video = document.getElementById("vid"); to refer to your <video> tag, it's shorter and cleaner than the first declaration.
Problem and question
In a reveal.js presentation, I want to include a long video file. I want to have the playblack stop at certain positions, so that I have time to explain to the audience what they’re seeing. Then, I want to have the playback continue when I click. How can I do this?
Unsuccessful attempts so far
My attempts are as follows. I split the video file into parts 1.webm, 2.webm, 3.webm and so on, such that each part ends where I want to have a break. My idea then is to
Override the keydown event of Reveal.js so that it doesn’t go to the next slide, but instead executes my Javascript. How can I do something like this?
<div class="slides">
<section class="video-stepper">
<video>
<source data-src="1.webm" type="video/webm" />
</video>
</section>
</div>
<script>
$(function() {
// How can I do this?
Reveal.addEventListener('click', function(event) {
if ($(event.currentSlide).hasClass('video-stepper')) {
event.preventDefault();
// change 'src' of the video element and start the playback.
}
});
});
</script>
Use fragments and autoplay the video when it is shown:
<div class="slides">
<section class="video-stepper">
<video class="fragment current-visible video-step">
<source data-src="1.webm" type="video/webm" />
</video>
<video class="fragment current-visible video-step">
<source data-src="2.webm" type="video/webm" />
</video>
<video class="fragment current-visible video-step">
<source data-src="3.webm" type="video/webm" />
</video>
</section>
</div>
<script>
$(function() {
Reveal.addEventListener('fragmentshown', function(event) {
if ($(event.fragment).hasClass('video-step')) {
event.fragment.play();
}
});
});
</script>
And some CSS taken from the question Hide reveal.js fragments after their appearance, so that the fragments stack on top of each other:
.fragment.current-visible.visible:not(.current-fragment) {
display: none;
height:0px;
line-height: 0px;
font-size: 0px;
}
However, this comes with some fading in and out, which looks bad. How can I avoid the fading?
When entering the video slide, you can basically disable reveal.js by calling Reveal.disableEventListeners(), then bind your own logic to the keydown event until you’ve stepped through all videos, before enabling reveal.js again with Reveal.addEventListeners().
Some additional effort is required to avoid flickering when transitioning to the next video. You can add a new <video> element with the new video, place it on top of the current <video> with the help of CSS z-index, play the new video, then remove the old.
HTML
<section class="video-stepper">
<!-- Unlike the other <video> element, this one is not absolutely
positioned. We hide it with CSS, but use it to reserve space
on the slide and compute the optimal width and height. -->
<video class="placeholder stretch">
<source src="1.webm">
</video>
<video class="video-step" data-sources='["1.webm","2.webm","3.webm"]'></video>
</section>
CSS
.video-stepper {
position: relative;
}
video.video-step {
position: absolute;
top: 0;
left: 0;
}
video.video-step.front {
z-index: 10;
}
video.placeholder {
visibility: hidden;
}
Javascript
This is a bit lengthy, but works as desired.
Reveal.addEventListener('slidechanged', function(event) {
if ($(event.currentSlide).hasClass('video-stepper')) {
// When we enter a slide with a step-by-step video, we stop reveal.js
// from doing anything. Below, we define our own keystroke handler.
Reveal.removeEventListeners();
// Set the width and height of the video so that it fills the slide.
var stretcher = $(event.currentSlide).find('video.placeholder').get(0);
var video = $(event.currentSlide).find('video.video-step').get(0);
video.setAttribute('width', stretcher.getAttribute('width'));
video.setAttribute('height', stretcher.getAttribute('height'));
// Convert the data-sources attribute to an array of strings. We will
// iterate through the array with current_video_index.
var sources = JSON.parse(video.getAttribute('data-sources'));
var current_video_index = 0;
// Add a <source> element to the video and set the 'src' to
// the first video.
var source = document.createElement('source');
source.setAttribute('src', sources[0]);
video.appendChild(source);
document.addEventListener('keydown', function step_through_videos(event) {
if (event.which == 39) {
// right arrow key: show next video
// For the next video, create a new <video> element
// and place it on top of the old <video> element.
// Then load and play the new. This avoids flickering.
var new_video = $(video).clone().get(0);
var new_video_source = $(new_video).children('source').get(0);
new_video_source.src = sources[current_video_index];
new_video.load();
$(new_video).addClass('front video-step');
$(new_video).insertAfter(video);
new_video.play();
// Wait a little before removing the old video.
new Promise((resolve) => setTimeout(resolve, 500)).then(function() {
video.remove();
video = new_video;
$(video).removeClass('front');
});
current_video_index = current_video_index + 1;
event.preventDefault();
} else if (event.which == 37) {
// left arrow key: return the counter to previous video
current_video_index = current_video_index - 1;
event.preventDefault();
}
if (0 > current_video_index || current_video_index >= sources.length) {
// Reinstall reveal.js handlers.
document.removeEventListener('keydown', step_through_videos, true);
Reveal.addEventListeners();
console.log('Added reveal.js event listeners.');
}
}, true);
}
});
I have an image that plays and stops the track perfectly. I am trying to alternate the image source from play.png to pause.png depending on if the track is playing or not.
Here's the code I have that is working to start/stop the audio, only with a static play.png image. How can I change the src attribute using javascript between pause.png and play.png?
<img src='play.png' onclick="aud_play_pause()">
<audio id="audio1">
<source src="audio1.mp3" type="audio/mp3">
</audio>
<script>
var myAudio=document.getElementById("audio1");
function aud_play_pause(){
if (myAudio.paused){
myAudio.play();
} else {
myAudio.pause();
}
}
</script>
You'll want to use javascript's DOM manipulation functions to change this like so:
var myAudio = document.getElementById("audio1");
var image = document.getElementsByTagName("img")[0];
function aud_play_pause(){
if (myAudio.paused){
myAudio.play();
image.setAttribute("src", "pause.png");
} else {
myAudio.pause();
image.setAttribute("src", "play.png");
}
}
Although it is better to reference the img element by its ID, I used its tag name since it was the only one there.
I'm using the following code to trigger fullscreen when a user clicks on the play button on a <video> element:
var video = $("#video");
video.on('play', function(e){
if (video.requestFullscreen) {
video.requestFullscreen();
} else if (video.mozRequestFullScreen) {
video.mozRequestFullScreen();
} else if (video.webkitRequestFullscreen) {
video.webkitRequestFullscreen();
}
});
But nothing happens when I click the play button.
Any idea's why?
EDIT: Here's my HTML code:
<video width="458" height="258" controls id='video' >
<source src='<?= bloginfo('template_directory'); ?>/inc/pilot.mp4' type="video/mp4">
<source src='<?= bloginfo('template_directory'); ?>/inc/pilot.ogv' type="video/ogg">
<source src='<?= bloginfo('template_directory'); ?>/inc/pilot.webm' type="video/webm">
</video>
There are a couple things going on here:
First, in your code, video is a jQuery object, not the actual video element. For a jQuery object, you can reference it like this:
var actualVideo = video[0]; // (assuming '#video' actually exists)
Second, for security and good user experience, browsers will only let you trigger full screen inside a user-triggered event, like a 'click'. You can't have every web page going to full screen as soon as you visit it, and you can cause a video to start playing automatically, which would violate that rule.
So an alternative solution would be to request fullscreen in a click event, like this:
var video = $("#video");
video.on('click', function(e){
var vid = video[0];
vid.play();
if (vid.requestFullscreen) {
vid.requestFullscreen();
} else if (vid.mozRequestFullScreen) {
vid.mozRequestFullScreen();
} else if (vid.webkitRequestFullscreen) {
vid.webkitRequestFullscreen();
}
});
Ideally, you'd probably want to build out a more complete player ui, but this should give you the general idea.
A less verbose way to toggle full screen combining answers from this and other questions.
This should handle all browser flavours: chromium- and webkit-based, firefox, opera, and MS-based browsers.
var p = document.querySelector('#videoplayer');
if (!window.isFs) {
window.isFs = true;
var fn_enter = p.requestFullscreen || p.webkitRequestFullscreen || p.mozRequestFullScreen || p.oRequestFullscreen || p.msRequestFullscreen;
fn_enter.call(p);
} else {
window.isFs = false;
var fn_exit = p.exitFullScreen || p.webkitExitFullScreen || p.mozExitFullScreen || p.oExitFullScreen || p.msExitFullScreen;
fn_exit.call(p);
}
p represents the DOM object of the video element, and window.isFs is just a random variable for storing the current fullscreen state.
If your player is a jQuery object then you can get the underlying DOM-element with var p = player.get(0).