Display several background videos - javascript

I'm trying to display different background videos with Javascript and with createElement method to only have one video tag node. By clicking on a link, the video is well displayed but not the others. I also checked the DOM Elements and both elements (id and src) of both <video> + <source> tags have been well switched (movie1 > movie2). It looks like the browser keep the first video even if the elements have been well modified in the DOM Elements.
<head>
<script>
var movieNow = "";
function playVideo(movie, mp4) {
if (movieNow!="") {
document.getElementById(movieNow).pause();
document.getElementById(movieNow).style.display="none";
document.getElementById(movieNow).id = movie;
document.getElementById('mysource').src = "videos/"+mp4+".mp4";
document.getElementsByTagName("Video").play();
document.getElementsByTagName("Video").style.display="block";
} else {
bckMovie = document.createElement("video");
bckMovie.id = movie;
bckMovie.className = "myvideo";
bckMovie.innerHTML = "<source src='videos/"+mp4+".mp4' type='video/mp4' id='mysource'>";
document.body.appendChild(bckMovie);
document.getElementById(movie).style.display="block";
document.getElementById(movie).play();
}
movieNow = movie;
}
</script>
<body>
Movie 1
Movie 2
...
</body>

Well you have some logical problems... Please examine this code at JsFiddle, that seems works as you need. https://jsfiddle.net/o5fdqurw/2/
<head>
<script>
var movieNow = "";
function playVideo(mp4) {
var movieNow = document.getElementById("movie");
if (movieNow !== null) {
movieNow.pause();
movieNow.style.display="none";
document.getElementById('mysource').src = "videos/"+mp4+".mp4";
movieNow.play();
movieNow.style.display="block";
} else {
bckMovie = document.createElement("video");
bckMovie.id = "movie";
bckMovie.className = "myvideo";
bckMovie.innerHTML = "<source src='videos/"+mp4+".mp4' type='video/mp4' id='mysource'>";
document.body.appendChild(bckMovie);
document.getElementById("movie").style.display="block";
document.getElementById("movie").play();
}
}
movieNow = movie;
</script>
<body>
Movie 1
Movie 2
...
</body>

Related

why does this keep playing same video instead of random new video?

I'm making a random order video player, adapting code from here but the same video just keeps playing, even though I can see (from text above the video) that the random ordering is working. Live version is here.
Is the problem with the appendChild meaning the new video is end of a list but the first in list keeps playing? I tried replaceChild but that didn't work.
<script type="text/javascript">
$(document).ready(function(){
var videos = [
[{type:'mp4', 'src':'carlos/one-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/two-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/three-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/four-carlostest.mp4'}],
[{type:'mp4', 'src':'carlos/five-carlostest.mp4'}]
];
// selecting random item from array as first to be played
var randomitem = videos[Math.floor(Math.random()*videos.length)];
// This function adds a new video source (dynamic) in the video html tag
function videoadd(element, src, type) {
var source = document.createElement('source');
source.src = src;
source.type = type;
element.appendChild(source);
}
// this function fires the video for particular video tag
function newvideo(src){
var vid = document.getElementById("myVideo");
videoadd(vid,src ,'video/ogg');
vid.autoplay = true;
vid.load();
vid.play();
}
// function call
newvideo(randomitem[0].src)
// Added an event listener so that everytime the video finishes ,a new video is loaded from array
document.getElementById('myVideo').addEventListener('ended',handler,false);
function handler(){
var newRandom = videos[Math.floor(Math.random()*videos.length)];
newvideo(newRandom[0].src)
document.getElementById("monitor").innerHTML = "randomitem is " + newRandom[0].src;
}
})
</script>
Also, if anyone can tell me why the autoplay never works that'd be appreciated, though it's the least of my problems.
I have kinda found this solution for your video playing one after other. now in your JS file, now you just will need to add your video src path.
var vidElement = document.getElementById('video');
var vidSources = [
"https://lutins.co.uk/carlos/one-carlostest.mp4",
"http://www.w3schools.com/html/movie.mp4"
];
var activeVideo = Math.floor((Math.random() * vidSources.length));
vidElement.src = vidSources[activeVideo];
vidElement.addEventListener('ended', function(e) {
// update the active video index
activeVideo = (++activeVideo) % vidSources.length;
if(activeVideo === vidSources.length){
activeVideo = 0;
}
// update the video source and play
vidElement.src = vidSources[activeVideo];
vidElement.play();
});
video {
width:350px;
}
<p>wowww you got it!</p>
<video src="https://lutins.co.uk/carlos/one-carlostest.mp4" id="video" autoplay muted playsinline></video>
Change the randomIt variable into a callback, only this way, it will generate new random number each time it get call.
// I have change randomitem into a function with ofcourse a proper name
var getRandomItem = function() {
return videos[Math.floor(Math.random()*videos.length)];
}
You should also call it properly like this:
//newvideo(randomitem[0].src) -> change it to
newvideo(getrandomItem().src)
There might also other adjustments requires for your code to work.

Cycling images with javascript

Why doesn't the second (hawk) image appear when the button is clicked? It goes straight to the else statement showing the ant image.
<!DOCTYPE html>
<html>
<body>
<script>
function changeImg() {
if (document.getElementById("cycle").src == "fox.jpg") {
document.getElementById("cycle").src = "hawk.jpg";
} else {
document.getElementById("cycle").src = "ant.jpg";
}
}
</script>
<button onclick = "changeImg()">change image</button>
<img id ="cycle" src ="fox.jpg"/>
</body>
</html>
Please add your script tags at the end of the body to make sure that your dom is rendered before accessing any elements. (like in my example)
The problem with your code is, that you need to add a new if for every new image you add. As you noticed yourself, it becomes hard to understand and debug.
For something like cycling, use an array and modulo operation on the index of that array.
With this solution, you can add as many images to the images array as you like, without touching the code/logic;
<!DOCTYPE html>
<html>
<body>
<button onclick="changeImg()">change image</button>
<img id="cycle" />
<script>
var imageElement = document.getElementById("cycle");
var images = ["fox.jpg", "hawk.jpg", "ant.jpg"]; // add as many images as you want
var counter = 0;
imageElement.src = images[counter] // set the initial image
function changeImg() {
counter = (counter + 1) % images.length;
imageElement.src = images[counter];
}
</script>
</body>
</html>
document.getElementById("cycle").src always has full url of image (example:https://example.loc/example/fox.jpg) and this is not similar from fox.jpg.
You need try another solution.Try use
cycle.getAttribute('src')
Example code:
function changeImg() {
let cycle = document.getElementById("cycle");
console.log(cycle.src,cycle.getAttribute('src')); // show real value and taribute
if (cycle.getAttribute('src') == "fox.jpg") {
cycle.src = "hawk.jpg";
} else {cycle.src = "ant.jpg";
}
}
Use getAttribute('src') if you want to access the actual contents of the attribute. Otherwise you get the resolved URL.
var cycle = document.getElementById("cycle");
if (cycle.getAttribute('src') == "fox.jpg") {
cycle.src = "hawk.jpg";
} else {
cycle.src = "ant.jpg";
}

Youtube API Iframe On Click

I really need some help with Youtube API.
<script type="text/javascript" src="http://www.youtube.com/player_api"></script>
<script type='text/javascript'>
window.onload=function(){
var player;
var $ = function(id) {
return document.getElementById(id);
}
var $$ = function(tagname) {
return document.getElementsByTagName(tagname);
}
var $$$ = function(classname) {
return document.getElementsByClassName(classname);
}
function onYouTubeIframeAPIReady() {
var videos = $$('iframe'), // the iframes elements
players = [], // an array where we stock each videos youtube instances class
playingID = null; // stock the current playing video
for (var i = 0; i < videos.length; i++) // for each iframes
{
var currentIframeID = videos[i].id; // we get the iframe ID
players[currentIframeID] = new YT.Player(currentIframeID); // we stock in the array the instance
// note, the key of each array element will be the iframe ID
videos[i].onmouseover = function(e) { // assigning a callback for this event
var currentHoveredElement = e.target;
if (playingID) // if a video is currently played
{
players[playingID].stopVideo();
}
players[currentHoveredElement.id].playVideo();
playingID = currentHoveredElement.id;
};
videos[i].onmouseout = function(e) { // assigning a callback for this event
var currentHoveredElement = e.target;
players[playingID].stopVideo();
playingID = currentHoveredElement.id;
};
}
}
onYouTubeIframeAPIReady();
}>
</script>
This is the Script, and for the PHP
$i = 1;
foreach($data['items'] as $child) {
$i++;
<iframe id="player<?php echo $i; ?>" width="270" height="180" data-src="http://www.youtube.com/embed/<?php echo $child['id']['videoId']; ?>?rel=0&wmode=Opaque&enablejsapi=1;showinfo=0;controls=0;autohide=1;modestbranding=1;showsearch=0;" frameborder="0" allowfullscreen style="position:relative;"></iframe>
}
It'll show the videos from youtube, and whenever you hover, it is autoplaying, onmouseout the video is stopping. But what i wanted to do is if hovered and clicked the iframe video, it goes to http://www.google.com/ link.
How am i supposed to do it?
Thanks in advance Guys.

playing multiple audio files

I am trying to create a playlist with the code below but I seem to be getting some errors. Firebug is saying that the play() is not a function. please help I have spent half of my day trying to find a solution. Here is my code:
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
var current, playlist;
current = 0;
function() {
current++;
var songs = Array("en_ra1.mp3", "en_ra2.mp3", "en_ra3.mp3", "en_ra0.mp3");
playlist = songs.length;
if (current == playlist) {
//do nothing or stop
} else {
this.playOptions = document.getElementById("audio").src = songs[current];
this.playOptions.play();
}
}
</script>
</head>
<body>
<audio id="audio" onended="loadplaylist()" src="ny_option1.mp3" controls ></audio>
Note:when I include the autoplay attribute it's works just fine despite the error showing in firebug console.
I'm not seeing where you declare the loadplaylist function, presumably a typo
in your function you are setting this.playOptions to the string returned from the array, not the player, I think your function should read something like this:
function loadplaylist() {
current++;
var songs = Array("en_ra1.mp3", "en_ra2.mp3", "en_ra3.mp3", "en_ra0.mp3");
playlist = songs.length;
if (current == playlist) {
//do nothing or stop
} else {
this.playOptions = document.getElementById("audio");
this.playOptions.src = songs[current];
this.playOptions.play();
}
}

video.js: force initialization of already manually initialized video

I'm dynamically generating and changing the content of my site with javascript.
I'm adding video files and the videojs-javascript-files by javascript and initialize the video by calling _V_(videos[i].id);.
However, initializing the video only works at the first time!
When I then change the content of the site and then move to the video's page again, initializing the video again (the video-tag has still the same id) does not work.
The browser's HTML5 videoplayer is there but not the videojs-styled one.
Is there any other way I could "force" initialization of the player? What could cause this problem?
This is my script:
videoPlayer = {
check: function() {
videos = document.getElementsByTagName("video");
if (videos.length > 0) {
this.init();
}
},
init: function() {
if (isPlayer) {
//alert("init");
for (var i = 0; i < videos.length; i++) var player = _V_(videos[i].id, {}, function() {
alert("player init!")
});
}
else {
this.build();
}
},
build: function() {
//alert("build");
if (isPlayer == false) {
var head = document.getElementsByTagName("head")[0];
var videoScript = document.createElement('script');
videoScript.type = 'text/javascript';
videoScript.src = './min/g=videojs';
var videocss = document.createElement('link');
videocss.type = 'text/css';
videocss.rel = 'stylesheet';
videocss.href = './min/g=videocss';
isPlayer = true;
videoScript.onload = this.init;
head.appendChild(videocss);
head.appendChild(videoScript);
}
}
}
Thank you very much in advance!
Have you tried creating a new video element and (re)initializing it instead of re-using the previous video element?
You can also try to "reset" everything, src, tracks, captions, etc with the new values
I know it's pretty late, but you could try checking the children of the video element. For example, if it already contains a div of class vjs-poster do nothing, else initialize video-js.

Categories