Need help in JavaScript to change and stop background video - javascript

In my site I have a video in background. Now I want to add two buttons, One will stop the video/start the video and one will stop the video and replace it with a image.
This is my site - site link
Can anyone please help me?
Thanks

you'll need to create the two buttons and style them as desired but here is the code you'll need to start/stop the video:
// assuming we're inside of your click listener callback
var video = document.querySelector('video');
if (video.playing) {
video.pause() // will bring the video to a halt
video.currentTime = 0; // brings it back to the beginning
} else {
video.play();
}
here is the code you'll need to replace the video with an image:
// assuming we're inside of your click listener callback
var video = document.querySelector('video');
var newImage = document.createElement('img');
newImage.src = 'source-of-your-image.jpg';
video.parentNode.insertBefore(newImage, video); // inserts img into DOM
video.parentNode.removeChild(video); // removes the video

You need some code like this to get the element by ID and for play/pause
var vid = document.getElementById("myVideo");
function playVid() {
vid.play();
}
function pauseVid() {
vid.pause();
}
And the HTML could be a[href]:
Play
Pause
To display the image you can use the poster attribute for video html5 tag. The image will display until the video is loaded and play is clicked and you can display it by reloading the video:
var vid = document.getElementById("myVideo");
function displayPoster() {
vid.load();
}

Related

How to DUPLICATE the [Play] & [Pause] button for audio playback on the very same page?

Im having trouble firing up the audio (playback+pause) on the same page.
My standard HTML5 audio player works perfect and has standard controlls like this:
<play title="Play spoken audio for the visually impaired">▶</play>
<pause title="Pause audio, and press again to resume play">❚❚</pause>
Now imagine you would like to have a simplified alternative play/pause controls elsewhere on the same page. Good idea right? Now my problem is, that if I add a separate more minimalistic play / pause control elsewhere on the page, then the first play/pause buttons dissappear entirely!
<play>▶</play>
<pause>❚❚</pause>
All that I want is to duplicate the functionality of the first play/pause and place them elsewhere on the page, allowing users on mobile to have the play/pause on another location of the page for ease of use.
So in summary, I would like to allow the user to controll the playback from two different places simultaneously. The main one has fancier layout, while the alternative one in location 2 has only play and pause toggle. Both should toggle if either one is pressed. (when play is pressed it shows as a pause button and when pause is pressed it becomes a play button).
What must I change in html and or javascript to achieve this? Thanks in advance!
The javascript looks like this:
window.onload = function(){
var myAudio = document.getElementsByTagName('audio')[0];
var play = document.getElementsByTagName('play')[0];
var pause = document.getElementsByTagName('pause')[0];
function displayControls() {
play.style.display = "block";
}
// check that the media is ready before displaying the controls
if (myAudio.paused) {
displayControls();
} else {
// not ready yet - wait for canplay event
myAudio.addEventListener('canplay', function() {
displayControls();
});
}
play.addEventListener('click', function() {
myAudio.play();
play.style.display = "none";
pause.style.display = "block";
});
pause.addEventListener('click', function() {
myAudio.pause();
pause.style.display = "none";
play.style.display = "block";
});
}
DEMO
So you have the following code...
var myAudio = document.getElementsByTagName('audio')[0];
var play = document.getElementsByTagName('play')[0];
var pause = document.getElementsByTagName('pause')[0];
Step-by-step breakdown...
document.getElementsByTagName('audio')[0]
Get the 0th (1st) element in the document that has the tag name audio.
document.getElementsByTagName('play')[0]
Get the 0th (1st) element in the document that has the tag name play.
Problem #1. You only register the first play button for the code. You must add code for the second play button.
document.getElementsByTagName('pause')[0]
Get the 0th (1st) element in the document that has the tag name pause.
Problem #2. Same problem as #1.
So the solution is:
var audio;
window.onload=function(){
audio=document.getElementsByTagName("audio")[0];
//YOU MUST REGISTER AN EVENT LISTENER FOR EVERY PLAY AND PAUSE BUTTON.
document.getElementsByClassName("playpause")[0].addEventListener("click",playpause);
document.getElementsByClassName("playpause")[1].addEventListener("click",playpause);
}
function playpause(){
var state;
if(audio.paused){
audio.play();
state="Pause";
}else{
audio.pause();
state="Play";
}
for(var i=0;i<document.getElementsByClassName("playpause").length;i++){
document.getElementsByClassName("playpause")[i].innerHTML=state;
}
}
<audio>
<source src="http://www.kozco.com/tech/32.mp3" type="audio/mpeg">
</audio>
<button class="playpause">Play</button>
<button class="playpause">Play</button>

Mp4 from Dropbox used with HTML5 video player, is not repeating

I'm working on a Squarespace website, and they don't allow video upload, so I'm using Dropbox to host a video.
The video starts playing, but he is not repeating.
This is the code:
<video id="htmlVideo" loop="loop">
<source type="video/mp4" src="https://www.dropbox.com/s/videoID/videoplayback.mp4?dl=1">
</video>
What could be the problem?
This is how I create the video
/*
function repeatForDropbox() {
console.log("repeatForDropbox caled" + htmlVideo );
}
*/
function createVideo() {
var video = document.createElement("video");
video.id = "htmlVideo";
video.loop = "loop";
var vidSource = document.createElement("source");
vidSource.type = "video/mp4";
vidSource.src = "https://www.dropbox.com/s/videoID/videoplayback.mp4?dl=1";
video.appendChild( vidSource );
var vidLocation = document.querySelector('#location').parentNode;
vidLocation.appendChild( video );
htmlVideo = document.querySelector(" #htmlVideo ");
// on load, play the video/mp4
window.onload = function () {
setTimeout(function() {
htmlVideo.play();
// htmlVideo.addEventListener("ended", repeatForDropbox);
// I tried here to make the video repeat, using the "ended" event listener
// so when the video ended, the video
// should get another <source> element(same src)
// and delete the old one
// but the event didn't fire
// I also tried htmlVideo.onended = function() {} , but same result
}, 500);
}
}
Just a guess, but I suspect this relates to redirects. A Dropbox share link with ?dl=1 on it will redirect you to a one-time use URL to download the content. Perhaps when the video player tries to loop, it tries to access the target of the redirect again.
This might show up in the network traffic from the browser, so it's worth taking a look. (E.g. the network tab of Chrome inspector, if you're using Chrome.)
I would see if squarespace will let you save the binary of the video into a text file and then import it with AJAX and save it to indexedDB before converting it to video.
Here's some links:
Display a video from a Blob Javascript
https://simpl.info/video/offline/
Just in case anyone still needs the solution, I found a workaround using jQuery:
$('video').on('ended', function () {
this.load();
this.play();
});
However, there is a slight delay between repeats!

Javascript stop and return to poster HTML 5 video

This is my javascript which pause and play the HTML 5 video when a button is pressed but I want to stop the video instead of pausing and returning to the video poster how can I achieve that?
function vidplay() {
var video = document.getElementById("bg-vid");
var button = document.getElementById("play");
if (video.paused) {
video.play();
} else {
video.pause();
}
}
Use load() method (although I believe changing the src attribute implicitly calls it):
...
if (video.paused) {
video.play()
} else {
load();
}
...
Note: this method re-loads the resource, thus depending on caching settings it may be re-downloaded causing unnecessary bandwidth and CPU usage.
The easiest way I have been able to find is to reset the source of the video. The other way to handle it would be to have a div with the poster image in that you swap out for the video.
The problem with this method is that by resetting the source you lose the playhead position so if that's important you'll also need to track the currentTime before resetting, and on play have the playhead set back to that currentTime value
<script>
var vid=document.getElementById('bg-vid');
vid.addEventListener("pause", resetVideo, false);
function resetVideo() {
// resets the video element by resetting the source
this.src = "video.mp4" // **source of video**
}
</script>

HTML 5 dynamically loaded videos causing black screen on iPad

I'm loading in videos dynamically by changing the video tag's src in code. When I try my code on an ipad (no idea if it works in the simulator or not), the first video plays fine but the next one just gives me a black screen. I have tried playing the second video first (to check for encoding issues) and it plays fine.
Here is my javascript function that loads/plays the video:
function loadVideo(video_path){
var vid = document.getElementById('v');
vid.src = video_path;
vid.load();
// play the video once it has loaded
vid.addEventListener('canplaythrough', function(e){
vid.style.display = "block";
vid.play();
}, false);
// hide the video container once the video has finished playing
vid.addEventListener('ended', function(e){
vid.style.display = "none";
}, false);
}
Called from my code like:
$('a').click(function(){
switch(video){
case 0:
loadVideo('path/to/myvideo.mp4');
break;
case 1:
loadVideo('path/to/myvideo2.mp4');
break;
case 2:
loadVideo('path/to/myvideo3.mp4');
break;
// etc
}
video++;
});
And my html inside the body tag:
<video id="v" type="video/h264" width="960" height="500"></video>
I have tried removing the video tag after each play and inserting it in again but that had no effect. Ideas welcome! :)
This isn't a solution for your exact question, but the concepts are there and you should be able to adjust it to your own code (the full extent of which I'm not privy to, of course). The following code is something I put together to have the VIDEO element load in and play the next video source in a queue automatically after the current video source is done.
The reason I use timeupdate to check for the video being "near" the end instead of just looking for the ended event is because the ended event is notoriously unreliable on older devices (such as the original iPad). You can use the ended event if you so wish, of course.
(function ($) {
var srcs = [
"video1.mp4",
"video2.mp4",
"video3.mp4",
"video4.mp4"
],
index = 0,
$video = $("#vid").attr("src", srcs[index]).bind("timeupdate", timeUpdateHandler),
video = $video.get(0);
function timeUpdateHandler(e) {
if (video.currentTime >= (video.duration - 0.1)) {
nextVideo();
}
}
function nextVideo() {
index++;
if (index === srcs.length) {
index = 0;
}
$video.attr("src", srcs[index]);
video.play();
}
})(jQuery);
Let me know if this helps you or if you have any questions.
You can use
<video onended="javascript:on_video_ended();"></video>
<script>
function on_video_ended(){
//javascript code goes here.
}
</script>

How do I load a video into a HTML5 page with javascript using onclick

I want to call a function onclick (which I know works) then load it into the page:
I'm trying to create a video element in HTML5 including some attributes for it.
I know it works because I tested it with the following alert:
alert("createSmallVideo has been called");
I've commented the alert now and I know the function is being called but why isn't the video being displayed on the web page:
function createSmallVideo(){
//alert("createSmallVideo has been called");
var video = document.createElement("video");
video.setAttribute("id", "VideoElement");
video.setAttribute("src", "videos/small.ogv");
video.setAttribute("controls", "controls");
video.setAttribute("preload", "auto");
document.getElementById("#VideoContainer").appendChild(video);
}
What am I doing wrong? Please help!
Because there is no element on your page with an id of #VideoContainer (or if there is there shouldn't be). An element Id cannot contain a #. If you open your JavaScript console you'll probably find a null reference error message. Try removing the # from your call to document.getElementById().
you can preload it with javascript too
function loadVideo(videoUrl){
var video;
try {
video = new Video();
} catch(e) {
video = document.createElement('video');
}
video.src = videoUrl;
bindOnce(video, 'canplaythrough', function() {alert("Loaded");});
video.onerror = function(e){alert("Error");};
video.load();
}

Categories

Resources