Randomized HMTL5 Video Array Playing Only One Video - javascript

I want to randomize a 179-video loop that is randomized anew each time the site is visited, but cannot get more than one video to play at a time.
{
function getRandom(min, max) {
if (min > max) {
return -1;
}
if (min == max) {
return min;
}
var r;
do {
r = Math.random();
}
while (r == 1.0);
return min + parseInt(r * (max - min + 1));
}
function randomSrc(videoId) {
console.log("randomSrc, " + videoId);
var vid = $("#" + videoId);
//var rndm = videoArray[getRandom(0, videoArray.length - 1)];
var rndm = "001.webm";
$(vid).attr("src", rndm).get(0).play();
$(vid).get(0).addEventListener('ended', function () {
randomSrc("v" + getRandom(1, 3));
}, false);
}
var videoArray = ["001.webm", "002.webm", "003.webm", "004.webm", "005.webm", "006.webm", "007.webm", "008.webm", "009.webm", "010.webm", "011.webm", "012.webm", "013.webm", "014.webm", "015.webm", "016.webm", "017.webm", "018.webm", "019.webm", "020.webm", "021.webm", "022.webm", "023.webm", "024.webm", "025.webm", "026.webm", "027.webm", "028.webm", "029.webm", "030.webm", "031.webm", "032.webm", "033.webm", "034.webm", "035.webm", "036.webm", "037.webm", "038.webm", "039.webm", "040.webm", "041.webm", "042.webm", "043.webm", "044.webm", "045.webm", "046.webm", "047.webm", "048.webm", "049.webm", "050.webm", "051.webm", "052.webm", "053.webm", "054.webm", "055.webm", "056.webm", "057.webm", "058.webm", "059.webm", "060.webm", "061.webm", "062.webm", "063.webm", "064.webm", "065.webm", "066.webm", "067.webm", "068.webm", "069.webm", "070.webm", "071.webm", "072.webm", "073.webm", "074.webm", "075.webm", "076.webm", "077.webm", "078.webm", "079.webm", "080.webm", "081.webm", "082.webm", "083.webm", "084.webm", "085.webm", "086.webm", "087.webm", "088.webm", "089.webm", "090.webm", "091.webm", "092.webm", "093.webm", "094.webm", "095.webm", "096.webm", "097.webm", "098.webm", "099.webm", "100.webm", "101.webm", "102.webm", "103.webm", "104.webm", "105.webm", "106.webm", "107.webm", "108.webm", "109.webm", "110.webm", "111.webm", "112.webm", "113.webm", "114.webm", "115.webm", "116.webm", "117.webm", "118.webm", "119.webm", "120.webm", "121.webm", "122.webm", "123.webm", "124.webm", "125.webm", "126.webm", "127.webm", "128.webm", "129.webm", "130.webm", "131.webm", "132.webm", "133.webm", "134.webm", "135.webm", "136.webm", "137.webm", "138.webm", "139.webm", "140.webm", "141.webm", "142.webm", "143.webm", "144.webm", "145.webm", "146.webm", "147.webm", "148.webm", "149.webm", "150.webm", "151.webm", "152.webm", "153.webm", "154.webm", "155.webm", "156.webm", "157.webm", "158.webm", "159.webm", "160.webm", "161.webm", "162.webm", "163.webm", "164.webm", "165.webm", "166.webm", "167.webm", "168.webm", "169.webm", "170.webm", "171.webm", "172.webm", "173.webm", "174.webm", "175.webm", "176.webm", "177.webm", "178.webm", "179.webm"];
//var rndm = videoArray[getRandom(0, videoArray.length - 1)];
var rndm = "004.webm";
$("#v1").attr("src", rndm);
randomSrc("v1" + getRandom(1, 3));
this.removeEventListener("load", arguments.callee, false);
})
</script>

Ahem? first you set the source of #v1 to "004.webm", then hard-code the source for element with id #v11, #v12, or #v13 to "001.webm", there is absolutely no way this is ever going to work like this.
Instead try something like this
var videoArray = [ ... ];
function getRandom(...) { ... };
function randomize(videoId) {
var vid = $('#' + videoId);
function setRandom() {
var index = getRandom(0, videoArray.length - 1)
vid.attr("src", videoArray[index]).get(0).play();
};
setRandom();
vid.bind("ended", function() {
setRandom();
});
};
randomize('v1');

Related

Insert two scripts in the same <script> tag without conflicts

I have to put these two scripts in a single tag without them coming into conflict but I can not make it. Please, how can I do it?
Also is it better to insert multiple scripts in the same tag?
Script 1
var sec = 04;
var hour = 00;
var time0, time1;
var delay=0;
var duringtime = 1000;
time1 = (hour *10000 + min * 100 + parseInt(sec)).toString();
console.log("time1", time1);
function refresh() {
........
}
}
refresh();
Script 2
var min = 80;
var max = 85;
var random = Math.floor(Math.random() * (max - min)) + min;
if (localStorage.getItem("stockcount_99")) {
if (localStorage.getItem("stockcount_99") >= duration) {
var value = random;
} else {
var value = localStorage.getItem("stockcount_99");
}
} else {
var value = random;
}
document.getElementById('divCounter').innerHTML = value;
var stockcount_99 = function() {
if (value <= stopValue) { // end count down. <= or >=
clearInterval(interval);
value = stopValue;
} else {
value = parseInt(value) - 1; // + 1 or - 1
localStorage.setItem("stockcount_99", value);
}
document.getElementById('divCounter').innerHTML = value;
};
var interval = setInterval(function() {
stockcount_99();
}, speedcontrol);
With the following method can I isolate the two scripts and thus prevent any conflicts?
(function() {
...script 1...
})()
(function() {
...script 2...
})()

js / css flip card game bug in shuffle function

I have created a js memory game. It has a 24-card grid, and it is supposed to shuffle randomly out of a deck of 15 cards in order to create a little variety. The game should be different every time. However, at random the game shuffles the initial deck and builds the board with 11 pairs and one non-pair of cards. Here's the whole js file:
`var score;
var cardsmatched;
var ui = $("#gameUI");
var uiIntro =$("#gameIntro");
var uiStats = $("# gameStats");
var uiComplete = $("#gameComplete");
var uiCards = $("#cards");
var uiScore = $(".gameScore");
var uiReset = $(".gameReset");
var uiPlay = $("#gamePlay");
var uiTimer = $("#timer");
var matchingGame = {};
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
$(function(){
init();
});
function init() {
uiComplete.hide();
uiCards.hide();
playGame = false;
uiPlay.click(function(e){
e.preventDefault();
uiIntro.hide();
startGame();
});
uiReset.click(function(e){
e.preventDefault();
uiComplete.hide();
reStartGame();
});
}
function startGame(){
uiTimer.show();
uiScore.html("0 seconds");
uiStats.show();
uiCards.show();
score = 0;
cardsmatched= 0;
if (playGame == false) {
playGame = true;
matchingGame.deck.sort(shuffle);
for (var i=0; i<25; i++){
$(".card:first-child").clone().appendTo("#cards");
}
uiCards.children().each(function(index) {
$(this).css({
"left" : ($(this).width() + 20) * (index % 6),
"top" : ($(this).height() + 20) * Math.floor(index / 6)
});
var pattern = matchingGame.deck.pop();
$(this).find(".back").addClass(pattern);
$(this).attr("data-pattern",pattern);
$(this).click(selectCard);
});
timer();
};
}
function timer(){
if (playGame){
scoreTimeout = setTimeout(function(){
uiScore.html(++score = "seconds");
timer();
}, 1000);
};
};
function shuffle() {
return 0.5 - Math.random();
}
function selectCard(){
if($(".card-flipped").size()> 1){
return;
}
$(this).addClass("card-flipped");
if($(".card-flipped").size() == 2) {
setTimeout(checkPattern, 1000);
};
};
function checkPattern(){
if (isMatchPattern()) {
$(".card-flipped").removeClass("card-flipped").addClass("card-removed");
if(document.webkitTransitionEnd){
$(".card-removed").bind("webkitTransitionEnd", removeTookCards);
}else{
removeTookCards();
} else {
$(".card-flipped").removeClass("card-flipped");
}
}
function isMatchPattern(){
var cards = $(".card-flipped");
var pattern = $(cards[0]).data("pattern");
var anotherPattern = $(cards[1]).data("pattern");
return (pattern == anotherPattern);
}
function removeTookCards() {
if (cardsmatched < 12) {
cardsmatched++;
$(".card-removed").remove();
}else{
$(".card-removed").remove();
uiCards.hide();
uiComplete.show();
clearTimeout(scoreTimeout);
}
}
function reStartGame(){
playGame = false;
uiCards.html("<div class='card'><div class='face front'></div><div class='face back'></div></div>");
clearTimeout(scoreTimeout);
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
startGame();
}
`

Javascripts code stops working

the problem it's about a roulette that spins every 1 min,
Problem : When I switch from one tab to another on google chrome or any other navigators, the script stops running and the roulette stops (and I need to go back to the tab again in order to make the script work)
image roulette = animation of game
//<![CDATA[
var myRoll = {
nbr : [14, 1, 13, 2, 12, 3, 11, 0, 4, 10, 5, 9, 6, 8 ,7],
initRoll : function(){
var Ccolor;
var nbrCtn = $(".nbr-ctn");
for(j = 0; j < 6 ; j++){
for(i = 0; i < this.nbr.length; i++){
Ccolor = "";
if(this.nbr[i] === 0 ){
Ccolor = "nbr-green";
}else if(this.nbr[i] > 7){
Ccolor = "nbr-black";
}else{
Ccolor = "nbr-red";
}
var elem = '<div class="nbr '+ Ccolor +'" >'+ this.nbr[i] +'</div>';
nbrCtn.append(elem);
}
}
},
lastResult : function(n){
Ccolor = "";
if(n === 0 ){
Ccolor = "nbr nbr-green";
}else if(n > 7){
Ccolor = "nbr nbr-black";
}else{
Ccolor = "nbr nbr-red";
}
var nbrResult = $(".lastResult > div").length;
if(nbrResult === 5 ){
$(".lastResult div:first-child").remove();
}
var elem = '<div class="circle '+ Ccolor +'" >'+ n +'</div>';
$(".lastResult").append(elem);
},
rollAnimation : function(offset, n){
var prog = $(".progress-line");
if(offset){
prog.width("100%");
var nbrCtn = $(".nbr-ctn");
nbrCtn.css("left" , "0px");
nbrCtn.animate({left: "-"+ offset +".5px"}, 6000, 'easeInOutQuint', function(){
myRoll.lastResult(n);
myRoll.countDown();
});
}
},
getRandomInt : function(min, max){
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
},
startRoll : function(n){
var nbrCtn = $(".nbr-ctn");
var gAnim = $("#game-animation");
var idx = this.nbr.indexOf(n) + this.nbr.length * 4;
var elmWidth = nbrCtn.find(".nbr").width();
var offset = idx * elmWidth - (gAnim.width() / 2);
offset = this.getRandomInt(offset + 5, offset + elmWidth - 5);
this.rollAnimation(offset, n);
},
countDown : function(){
var prog = $(".progress-line");
var gameStatus = $(".rolling > span");
prog.animate({width : "0px"}, {
duration: 30000,
step: function(now){
var rt = (now*3) / 100;
gameStatus.html("Closing in " + rt.toFixed(2));
},
complete: function(){
// when the progress bar be end
gameStatus.html("Rolling ...");
myRoll.startRoll(myRoll.getRandomInt(0, 14));
},
easing: "linear"
});
}
};
window.onload = function(){
myRoll.initRoll();
myRoll.countDown();
};
//]]>
For this you need to implement things in following way (this is just way out).
Basic concept behind bellow code is calculate lag between tab switch and set current state accordingly.
var prevTime,curTime;
var rate = 500; //(miliseconds) you can set it.
function update()
{
var diffTime = curTime - prevTime;
if (diffTime >= rate)
{
//check if difference is more than step value then calculate
//current state accordingly. so you will always be updated as you calculating lags.
// e.g. diffTime = 1500;
// you will need to jump Math.floor(diffTime/rate) which is 3.
// calculate current state.
//your code....
prevTime = curTime;
}
requestAnimationFrame(update);
}

Javascript: Grab an array and sum all values

In my project, users can add timecode in and out points for their project, and the project automatically figures out the total duration of the timecode. But I want to add a function that will take all the available timecode durations, convert them to seconds, add them together, then convert the final number back to timecode and put it in a text input.
This is my code, but I keep getting syntax errors:
function timeToSeconds(t) {
var tc = t.split(':');
return parseInt(tc[0])*3600 + parseInt(tc[1])*60 + parseInt(tc[2]);
}
function tcDuration(tcin, tcout) {
function z(n){return (n<10?'0':'') + n;}
var duration = timeToSeconds(tcout) - timeToSeconds(tcin);
var hoursmins = Math.floor(duration / 60);
return z(Math.floor(hoursmins/60)) + ':' + z(hoursmins % 60) + ':' + z(duration % 60);
}
// Run this function every time a film_tc_out cell is changed
function film_tc_Duration() {
if (document.getElementById("film_tc_in").value == '') {var film_tc_in = '00:00:00';} else { var film_tc_in = document.getElementById("film_tc_in").value;}
if (document.getElementById("film_tc_out").value == '') {var film_tc_out = '00:00:00';} else { var film_tc_out = document.getElementById("film_tc_out").value;}
document.getElementById("film_tc_duration").value = tcDuration(film_tc_in, film_tc_out);
}
// Run this function every time a src_tc_out cell is changed
function src_tc_Duration() {
if (document.getElementById("src_tc_in").value == '') {var src_tc_in = '00:00:00';} else { var src_tc_in = document.getElementById("src_tc_in").value;}
if (document.getElementById("src_tc_out").value == '') {var src_tc_out = '00:00:00';} else { var src_tc_out = document.getElementById("src_tc_out").value;}
document.getElementById("src_tc_duration").value = tcDuration(src_tc_in, src_tc_out);
}
// Run this function every time a src_wd_out cell is changed
function src_wd_Duration() {
if (document.getElementById("src_wd_in").value == '') {var src_wd_in = '00:00:00';} else { var src_wd_in = document.getElementById("src_wd_in").value;}
if (document.getElementById("src_wd_out").value == '') {var src_wd_out = '00:00:00';} else { var src_wd_out = document.getElementById("src_wd_out").value;}
document.getElementById("src_wd_duration").value = tcDuration(src_wd_in, src_wd_out);
}
function total_tc_Duration() {
var val = document.getElementsByClassName('.asset_src_tc_duration');
var total_tc = 0;
var v;
for (var i = 0; i < val.length; i++) {
v = timeToSeconds(val[i]);
if (!isNaN(v)) total_tc += v;
}
return (total_tc);
}
function updateAssetTimecode() {
document.getElementById("timecode_total").value = total_tc_Duration();
}
Update: I've rewritten the For Loop to see if that helps - it currently gives me an answer now, although the answer is always "0". It's not spitting out any errors but it seems to think the variable val isn't a number?
Your tcDuration function won't work like you expect. You don't subtract the already calculated hours before doing the minutes calculation and the same with seconds.
function tcDuration(tcin, tcout) {
function z(n){return (n<10?'0':'') + n;}
var duration = timeToSeconds(tcout) - timeToSeconds(tcin);
var hoursmins = Math.floor(duration / 60);
return z(Math.floor(hoursmins / 60)) + ":" + z(hoursmins % 60) + ":" + z(duration % 60);
}

Having issues with live calculations, calculating each key stroke

I have a table that calculates a total depending on the input the user types. My problem is that the jquery code is calculating each key stroke and not "grabbing" the entire number once you stop typing. Code is below, any help woud be greatly appreciated.
$(document).ready(function() {
$('input.refreshButton').bind('click', EstimateTotal);
$('input.seatNumber').bind('keypress', EstimateTotal);
$('input.seatNumber').bind('change', EstimateTotal);
});
//$('input[type=submit]').live('click', function() {
function EstimateTotal(event) {
var tierSelected = $(this).attr('data-year');
var numberSeats = Math.floor($('#numberSeats_' + tierSelected).val());
$('.alertbox_error_' + tierSelected).hide();
if (isNaN(numberSeats) || numberSeats == 0) {
$('.alertbox_error_' + tierSelected).show();
} else {
$('.alertbox_error_' + tierSelected).hide();
var seatHigh = 0;
var seatLow = 0;
var seatBase = 0;
var yearTotal = 0;
var totalsArray = [];
var currentYear = 0;
$('.tier_' + tierSelected).each(function() {
seatLow = $(this).attr('data-seat_low');
firstSeatLow = $(this).attr('data-first_seat_low');
seatHigh = $(this).attr('data-seat_high');
seatBase = $(this).attr('data-base_cost');
costPerSeat = $(this).attr('data-cost_per_seat');
years = $(this).attr('data-year');
seats = 0;
if (years != currentYear) {
if (currentYear > 0) {
totalsArray[currentYear] = yearTotal;
}
currentYear = years;
yearTotal = 0;
}
if (numberSeats >= seatHigh) {
seats = Math.floor(seatHigh - seatLow + 1);
} else if (numberSeats >= seatLow) {
seats = Math.floor(numberSeats - seatLow + 1);
}
if (seats < 0) {
seats = 0;
}
yearTotal += Math.floor(costPerSeat) * Math.floor(seats) * Math.floor(years) + Math.floor(seatBase);
});
totalsArray[currentYear] = yearTotal;
totalsArray.forEach(function(item, key) {
if (item > 1000000) {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('Contact Us');
} else {
$('.totalCost_' + tierSelected + '[data-year="' + key + '"]').append('$' + item);
}
});
}
}
You'll need a setTimeout, and a way to kill/reset it on the keypress.
I'd personally do something like this:
var calc_delay;
$(document).ready(function() {
$('input.refreshButton').bind('click', runEstimateTotal);
$('input.seatNumber').bind('keypress', runEstimateTotal);
$('input.seatNumber').bind('change', runEstimateTotal);
});
function runEstimateTotal(){
clearTimeout(calc_delay);
calc_delay = setTimeout(function(){ EstimateTotal(); }, 100);
}
function EstimateTotal() {
....
What this does is prompt the system to calculate 100ms after every keypress - unless another event is detected (i.e. runEstimateTotal is called), in which case the delay countdown resets.

Categories