i have this code for autoplay (playlist) movie
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Movie Playlist</title>
<script>
var videoPlayer;
var video_count = 1;
window.onload = function (){
videoPlayer = document.getElementById("homevideo");
videoPlayer.addEventListener("ended", function (){
video_count++;
if (video_count == 6) video_count = 1;
var nextVideo = video_count+".mp4";
videoPlayer.src = nextVideo;
}, false);
}
</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div style="width:100%;margin:0px auto;">
<video id="homevideo" width="100%" autoplay autobuffer src="1.mp4"></video>
</div>
on the code above, i have 5 .mp4 movie, but if i have more than 5 .mp4 movie, the 6.mp4, 7.mp4 and other will not be played. so, how can i dynamically set the movie count pure using html5 or javascript?
You are better off having your server provide this information.
But for your existing approach, I'm assuming your video names are in sequential order ... so 1.mp4, 2.mp4, 3.mp4, etc ... so you could keep looping through the videos while increasing the count, and once a video fails to load at a given video_count, you can know that it is the limit and loop back to the start if you wanted.
function videoExists(videoUrl){
var http = new XMLHttpRequest();
http.open('HEAD', videoUrl, false);
http.send();
return http.status != 404;
}
So, for example ...
var videoPlayer;
var video_count = 1;
var video_max = 0;
window.onload = function (){
videoPlayer = document.getElementById("homevideo");
videoPlayer.addEventListener("ended", function (){
var nextVideo = (video_count+1)+".mp4";
if(video_count <= video_max || videoExists(nextVideo)){
videoPlayer.src = nextVideo;
video_count++;
}else{
video_max = video_count;
//reset back to original video
video_count = 1;
videoPlayer.src = video_count+".mp4";
}
}, false);
}
I didn't test the code, but you should get the idea. Please let me know if you have any questions about this approach.
Related
When the user is changing the tab. I want to play notification sound and change the title of the page to grab attention.
How can I do it with JavaScript.
This is the code I have used and isn't working.
<script>
var message = "Come Back...";
var original = document.title;
window.onblur = function () { document.title = message; }
window.onfocus = function () { document.title = original; }
</script>
You can achieve it very easily:
Here is the full example:
<html>
<head>
<meta charset="UTF-8" />
<script src="script.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
</head>
<body>
<h1>Focus</h1>
</body>
<script>
setInterval(checkFocus, 100);
var audio = new Audio(
"https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"
);
audio.loop = true;
function checkFocus() {
if (document.hasFocus()) {
document.title = "Main Title";
audio.pause();
} else {
document.title = "Title Change";
audio.play();
}
}
</script>
</html>
Working Demo
Working App Demo Code stackblitz.com
I'm trying to get the image to change based on one second timer, but the image stays one the first object in the array
the code I have so far is
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 8 - Jackhammer Man</title>
<script type="text/javascript">
var jackhammers = new Array();
jackhammers[0] = "<img src='Images/jackhammer0.gif'>";
jackhammers[1] = "<img src='Images/jackhammer1.gif'>";
jackhammers[2] = "<img src='Images/jackhammer2.gif'>";
jackhammers[3] = "<img src='Images/jackhammer2.gif'>";
jackhammers[4] = "<img src='Images/jackhammer4.gif'>";
jackhammers[5] = "<img src='Images/jackhammer5.gif'>";
jackhammers[6] = "<img src='Images/jackhammer6.gif'>";
jackhammers[7] = "<img src='Images/jackhammer7.gif'>";
jackhammers[8] = "<img src='Images/jackhammer8.gif'>";
jackhammers[9] = "<img src='Images/jackhammer9.gif'>";
jackhammers[10] = "<img src='Images/jackhammer10.gif'>";
var curJackhammer;
function bounce() {
var img = document.getElementsByTagName("img");
var i = 0 ;
for (i = 0; i<10;i++) {
if(jackhammers[i].src == img.src) {
if(i === jackkhammers.length) {
img.src = jackhammers[0].src;
break;
}
img.src = jackhammers[i+1].src;
break;
}
}
}
</script>
</head>
<body>
<img onMouseOver="setInterval(function(){bounce},1000);" onMouseOut="clearInternval(fuction(){bounce};" src="Images/jackhammer0.gif" id="hammer" name="hammerman" alt="Jackhammer Man">
</body>
</html>
The issue I'm coming across is the mouseover event will not activate, I am having trouble finding the error in my code as the debuggers I have aren't finding any. Any help trying to get the mouseover function of the image changing ever so often would be appreciated.
you have a typo if(i === jackkhammers.length)
jackhammers[x] has no src property so to get its value use it without .src
instead of
onMouseOver="setInterval(function(){bounce},1000);"
write:
onMouseOver="setInterval(function(){bounce();},1000);"
var img = document.getElementsByTagName("img");
This returns a NodeList, or an array of elements. You need to access the index of this element with [0]
Or better yet, use querySelector which returns the first element in a NodeList
You keep referring to the src property of items in the jackhammers array:
img.src = jackhammers[0].src;
even though items in that array are strings, not objects.
Also, there's a typo here:
if(i === jackkhammers.length) {
These kinds of errors would be immediately visible the with dev tools of your browser of choise. Put a breakpoint to where you suspect things go wrong and start investigating variables and your assumptions while stepping through the code.
See here: http://www.creativebloq.com/javascript/javascript-debugging-beginners-3122820
Updated code changed a few things around based on some advice from my mentor.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Lab 8 - Jackhammer Man</title>
<script type="text/javascript">
var jackhammers = new Array(11);
jackhammers[0] = "Images/jackhammer0.gif";
jackhammers[1] = "Images/jackhammer1.gif";
jackhammers[2] = "Images/jackhammer2.gif";
jackhammers[3] = "Images/jackhammer3.gif";
jackhammers[4] = "Images/jackhammer4.gif";
jackhammers[5] = "Images/jackhammer5.gif";
jackhammers[6] = "Images/jackhammer6.gif";
jackhammers[7] = "Images/jackhammer7.gif";
jackhammers[8] = "Images/jackhammer8.gif";
jackhammers[9] = "Images/jackhammer9.gif";
jackhammers[10] = "Images/jackhammer10.gif";
var curJackhammer = 0;
var direction;
var begin;
function bounce(){
if(curJackhammer == 10)
curJackhammer = 0;
else
++curJackhammer;
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer].src;
if(curJackhammer == 0)
direction = "up";
else if(curJackhammer == 10)
direction = "down";
document.getElementsByTagName("img")[0].src = jackhammers[curJackhammer];
}
function startBouncing(){
if (begin)
clearInterval (begin);
begin = setInterval("bounce()",90);
}
</script>
</head>
<body>
<h1>Jackhammer Man</h1>
<p><img onMouseOver="startBouncing();" onMouseOut="clearInterval(begin);" src="Images/jackhammer0.gif" height="113" width="100" alt="Image of a man with a jackhammer." /></p>
</body>
</html>
>
Used firebug to step into code, works once I set into it but simply putting a mouse over nothing happens.
I am trying to write code to play a continous loop of two videos. I have tried to do so by this code, but it has not been done. Being new to html5 and javascript need help to make required corrections.
<!doctype html>
<html><head>
<script>
var videoSource = new Array();
videoSource[0]="videfirst.mp4";
videoSource[1]="videosecond.mp4";
var videoCount = videoSource.length;
document.getElementById("myVideo").setAttribute("src",videoSource[0]);
function videoPlay(videoNum)
{
document.getElementById("myVideo").setAttribute("src",videoSource [videoNum]);
document.getElementById("myVideo").load();
document.getElementById("myVideo").play();
}
document.getElementById('myVideo').addEventListener ('ended',myHandler,false);
function myHandler() {
i++;
if(i == (videoCount-1)){
i = 0;
videoPlay(i);
}
else{
videoPlay(i);
}
}
</script>
</head>
<body>
<video controls height="180" width="300" id="video" >
</video>
</body>
</html>
I am trying to write some javascript code with some jQuery that will play a random sound file (selected from an array) to play periodically by setting a random amount of time to delay between sounds. So far, I have gotten the random song selector to work. However, there seems to be an issue with the recursion in the playMusic function. Only two songs will play back-to-back then stop with no delay between the songs.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var randInterval = 0;
var songList = ["song1","song2","song3","song4","song5"];
var songHTML;
function getRandomSong(){
var randSong = songList[Math.floor(Math.random()*songList.length)];
songHTML = "<source src='music/" + randSong + ".mp3'>" +
"<source src='music/" + randSong + ".ogg'>";
return songHTML;
}
function setRandomInterval(){
randInterval = Math.floor((Math.random()*60)+60);
return randInterval;
}
function playMusic(){
var delayTime = setRandomInterval();
$(document).ready(function(){
$('#myAudio').html(getRandomSong());
$('#myAudio').prop("volume", 0.05);
$('#myAudio').get(0).play();
});
$('#myAudio').on('ended', function(){
$('#myAudio').delay(delayTime).queue(function(){
return playMusic();
});
});
}
</script>
</head>
<body onload="playMusic()">
<div>
<audio controls id="myAudio" autoplay>
</audio>
</div>
</body>
</html>
I figured out how to do this. Below is the code that works correctly. I removed any JQuery related code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var randInterval = 0;
var songList = ["song1","song2","song3","song4","song5"];
var myAudio = new Audio("music/" + songList[Math.floor(Math.random()*songList.length)] + ".mp3");
//Generates a random song, sets it attributes/properties, and
//appends a file extension that works with the browser.
function getRandomSong(){
var randSong = songList[Math.floor(Math.random()*songList.length)]
if (myAudio.canPlayType('audio/mp3;')) {
myAudio.src="music/" + randSong + ".mp3";
} else {
myAudio.src="music/" + randSong + ".ogg";
}
myAudio.id="myAudio";
myAudio.volume=0.15;
myAudio.load();
myAudio.controls=false
myAudio.preload=false;
}
//Sets a random interval for the setTimeout Function with the
//'variation' parameter being a random amount of time in
//seconds, and the 'range' parameter being a set amount of time
//in seconds.
function getRandomInterval(variation, range){
randInterval = Math.floor((Math.random()*1000*variation)+(1000*range));
return randInterval;
}
//Gets a random song and plays that song.
function playMusic(){
getRandomSong();
myAudio.play();
}
</script>
</head>
<body>
<script type="text/javascript">
//Plays music on page load.
playMusic();
//Event Listener that will start a new song after a pause
//of randomly determined length.
myAudio.addEventListener('ended', function(){setTimeout(function(){playMusic();}, getRandomInterval(2,2));}, false);
</script>
</body>
</html>
I want to play some YouTube video in my Metro app. I embed YouTube video in my app using YouTube Iframe API(Link). Then I meet a serious problem of memory leak. If I embed a YouTube video and then remove it, the memory will increase about 5MB and nerver decrease any more. Demo code is here:
default.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>iframeTest</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
<!-- iframeTest references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body style ="">
<button id="remove" style="display:block; float:left;">remove a video</button>
<button id="add" style="display:block; float:left;">add a video</button>
</body>
</html>
default.js fragment:
document.getElementById("remove").addEventListener("click", function () {
var ifrs = document.querySelectorAll('div');
if (ifrs.length > 0) {
document.body.removeChild(ifrs[ifrs.length - 1]);
}
});
document.getElementById("add").addEventListener("click", function(){
var testYoutubeDiv = document.createElement('div');
testYoutubeDiv.style.cssFloat = 'left';
testYoutubeDiv.style.width = '400px';
testYoutubeDiv.style.height = '300px';
MSApp.execUnsafeLocalFunction(function () {
testYoutubeDiv.innerHTML = "<iframe id='player' type='text/html' width='400' height='300' src='http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1&origin=http://example.com' frameborder='0'></iframe>";
});
document.body.appendChild(testYoutubeDiv);
});
Then, I write a similar .html file and test it in IE10.0 and Chrome. I find IE10.0 also has memory leak problem but chrome has not. And the memory leak problem in IE10.0 is less serious than in Metro App.
test html code was here:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>iframeTest</title>
<script type = "text/javascript">
function load() {
document.getElementById("remove").addEventListener("click", function () {
var ifrs = document.querySelectorAll('div');
if (ifrs.length > 0) {
document.body.removeChild(ifrs[ifrs.length - 1]);
}
});
document.getElementById("add").addEventListener("click", function () {
var testYoutubeDiv = document.createElement('div');
testYoutubeDiv.style.cssFloat = 'left';
testYoutubeDiv.style.width = '400px';
testYoutubeDiv.style.height = '300px';
testYoutubeDiv.innerHTML = "<iframe id='player' type='text/html' width='400' height='300' src='http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1&origin=http://example.com' frameborder='0'></iframe>";
document.body.appendChild(testYoutubeDiv);
});
}
</script>
</head>
<body onload ="load()">
<button id="remove" style="display:block; float:right;">remove a video</button>
<button id="add" style="display:block; float:right;">add a video</button>
</body>
</html>
I notice that IE(and maybe Metro App) does not use WebKit Engine to deal with javascript code. Is there any way to reduce memory leak in Metro App?
Create an iframe in html file
<iframe id="ifr_video"></iframe>
And then add a source to that iframe using javascript, while adding source find the id of YouTube URL by spliting, for example if the YouTube URL is http://www.youtube.com/watch?v=ZnehCBoYLbc, the ID is ZnehCBoYLbc, then define the source like the following for finding ID and adding source
var Url_splits = Youtube_Video_url.split("/");
var Url_length = Url_splits.length;
var Ytube_id = Url_splits[(Url_length - 1)];
document.getElementById("ifr_video").src = "http://www.youtube.com/embed/" + Ytube_id;
In HTML
<video id="VideoSource" style="border:1px solid black;" controls="controls" ></video>
<iframe class="youtube-player" id="ifr_video" type="text/html" width=100% height=100% allowfullscreen frameborder="0"></iframe>
In JS (inside ready function)
id("VideoSource").msPlayToSource.connection.addEventListener("statechanged", playToSrcStateChangeHandler);
function playToSrcStateChangeHandler(eventIn) {
var states = Windows.Media.PlayTo.PlayToConnectionState;
if (eventIn.currentState === states.disconnected) {
WinJS.log && WinJS.log("PlayTo connection state: Disconnected", "sample", "status");
} else if (eventIn.currentState === states.connected) {
WinJS.log && WinJS.log("PlayTo connection state: Connected", "sample", "status");
} else if (eventIn.currentState === states.rendering) {
WinJS.log && WinJS.log("PlayTo connection state: Rendering", "sample", "status");
}
}
Video_Path = "http://www.youtube.com/embed/" + new_id;
//new_id is the Youtube video id For example,..
in http://www.youtube.com/watch?v=ZnehCBoYLbc , id is ZnehCBoYLbc
function playYouTubeVideo(Video_Path) {
document.getElementById("ifr_video").src = Video_Path;
id("VideoSource").style.display='none';
}
function playWebContent(Video_Path) {
document.getElementById("ifr_video").style.display = 'none';
var localVideo = id("VideoSource");
var videoStabilization = Windows.Media.VideoEffects.videoStabilization;
localVideo.src = Video_Path;
localVideo.play();
}
Reference: http://code.msdn.microsoft.com/windowsapps/Media-PlayTo-Sample-fedcb0f9