Looping gifs is crashing my html page - javascript

I have a loop that creates 4 divs that is generating random numbers. those divs are also assigned gifs. I have another loop that is fading in and fading out those images. After clicking the gifs a few times to generate the random number guesses the whole page freezes up, how do i fix this? does it have to do with the cache? I am looping the the fadeIn and fadeOut after the on click function.
here is my code:
var startGame = function () {
$(".crystals").empty();
var images = [
'https://thumbs.gfycat.com/WeightyAgreeableDanishswedishfarmdog-max-1mb.gif',
'http://31.media.tumblr.com/224595f52671895de1608de69012d1d6/tumblr_nfk2itPn1tqou9go1_500.gif',
'http://pictures.willowsgraphics.com/compybackup/pics/animatedicons/shootingstar.gif',
'https://media.giphy.com/media/yfoeIMBjzVw52/giphy.gif',
];
randomNumber = Math.floor(Math.random() * 101) + 19;
$("#result").html('Catch this many stars: ' + randomNumber);
for (var i = 0; i < 4; i++) {
var cardRandom = Math.floor(Math.random() * 11) + 1;
var crystal = $("<div>");
crystal.attr({
"class": 'crystal',
"data-random": cardRandom
});
crystal.css({
"background-image": "url('" + images[i] + "')",
"background-size": "cover",
"background-position": "center"
});
$(".crystals").append(crystal);
$("#previous").html("Total Score: " + previousNumber);
}
}
startGame();
$(document).on("click", '.crystal', function () {
var num = parseInt($(this).attr('data-random'));
var loopImages = function () {
$('.crystal').fadeIn(1500, function () {
$('.crystal').fadeOut(1500, loopImages);
});
}
loopImages();
previousNumber += num;
$("#previous").html("Total Score: " + previousNumber);
if (previousNumber > randomNumber) {
losses++;
$("#losses").html("Your Losses: " + losses);
previousNumber = 0;
startGame();
}
else if (previousNumber === randomNumber) {
wins++;
$("#wins").html("Your Wins: " + wins);
previousNumber = 0;
startGame();
}
});

I figured it out, i was trying to loop the fades for the wrong div :)

Related

Timer for individual <div>

I'm currently trying to set a timer for each div created, whereby each div has a background color of green or red depending on if there are detections in the webRTC video. Is there a way to assign a timer to the divs individually? Or maybe to only check for my own video? I've tried something like below, but it does not work when there are more than 1 people in the call, as "time" will be a global variable. I've also tried something like time = Math.ceil((time+1)/checkerBox.length) , but it does not seem to work too. Any pointers will be helpful
function checker(){
var time =0;
var timer = setInterval(function (){
for(var i=0;i<checkerBox.length;i++){
if(checkerBox[i].style.backgroundColor=="red"){
time = time + 1;
console.log("Box" + videoNum[i].innerHTML + " is not present for : " + checkerBox[i].innerHTML + " seconds");
}else{
time = 0;
}
//Exceed time
if(checkerBox[i].innerHTML == 30){
setTimeout(function(){
takeScreenshot(videoNum[i-1]);
}, 100);
time = 0;
}
checkerBox[i].innerHTML = time;
}
},1000)
}
Update : I ended up using arrays
var takenFrom;
var d = new Date();
let timeKeep = new Array(0,0,0,0,0,0,0,0,0,0,0);
let screenShots = new Array(0,0,0,0,0,0,0,0,0,0,0);
function checker(){
timer = setInterval(function (){
for(var i=0;i<=(checkerBox.length)-1;i++){
tableRow[i+1].cells[2].innerHTML = timeKeep[i]
tableRow[i+1].cells[3].innerHTML = screenShots[i]
if(flag[i].innerHTML=="0"){
checkerBoxFalse(checkerBox[i]);
timeKeep[i] = timeKeep[i] + 1;
console.log("Box" + videoNum[i].innerHTML + " is not present for : " + tableRow[i+1].cells[2].innerHTML + " seconds");
if(tableRow[i+1].cells[2].innerHTML == 10 ){
takenFrom = "Box" + videoNum[i].innerHTML + "minute" + d.getMinutes() + " room" + ROOM_ID
takeScreenshot(videoNum[i],takenFrom);
screenShots[i] = screenShots[i] + 1;
timeKeep[i] = 0;
}
} else if(flag[i].innerHTML== "1"){
checkerBoxTrue(checkerBox[i]);
timeKeep[i] = 0;
}
}
},1000)
}
Yes:
for (let div of divs) {
setInterval(function() {
//do something with div
}, 1000);
}
let is block scoped, so each setInterval will have its own div.

What is the error in the startAction() function?

After I destroying 2 fruits by hovering my mouse over them the third fruit doesn't show up.
var playing = false;
var score;
var trialsLeft;
var step;
var action;
var fruits = ['apple', 'banana', 'cherries', 'grapes', 'mango', 'orange', 'peach', 'pear', 'watermelon'];
$(function() {
$("#startreset").click(function() {
//we are playing
if (playing == true) {
location.reload();
} else {
playing = true;
score = 0; //set score to 0
$("#scorevalue").html(score);
$("#trialsLeft").show();
trialsLeft = 3;
addHearts();
$("#gameOver").hide();
$("#startreset").html("Reset Game");
startAction();
}
});
$("#fruit1").mouseover(function() {
score++;
$("#scorevalue").html(score);
// document.getElementById("slicesound").play();
$("#slicesound")[0].play();
clearInterval(action);
$("#fruit1").hide("explode", 500);
setTimeout(startAction, 500);
});
function addHearts() {
$("#trialsLeft").empty();
for (i = 0; i < trialsLeft; i++) {
$("#trialsLeft").append('<img src="images/heart.png" class="life">');
}
}
})
So startAction() function is supposed to create fruits. I have images of fruits saved in my folder and I decide which fruit to show by random function and array of fruits.
function startAction() {
$("#fruit1").show();
chooseFruit(); //choose a random fruit
$("#fruit1").css({ 'left': Math.round(550 * Math.random()), 'top': -50 }); //random position
step = 1 + Math.round(5 * Math.random());
action = setInterval(function () {
$("#fruit1").css('top', $("#fruit1").position().top + step);
if ($("#fruit1").position().top > $("#fruitsContainer").height()) {
if (trialsLeft > 1) {
$("#fruit1").show();
chooseFruit();
$("#fruit1").css({ 'left': Math.round(550 * Math.random()), 'top': -50 });
step = 1 + Math.round(5 * Math.random()); // change step
trialsLeft--;
addHearts();
} else {
playing = false;
$("#startreset").html("Start Game");
$("#gameOver").show();
$("#gameOver").html('<p>Game Over!</p><p>Your score is ' + score + '</p>');
$("#trialsLeft").hide();
stopAction();
}
}
}, 10);
}
function chooseFruit() {
$("#fruit1").attr('src', 'Images/' + fruits[Math.round(8 * Math.random())] + '.png');
}
function stopAction() {
clearInterval(action);
$("#fruit1").hide();
}
The problem was the function $("#fruit1").hide("explode",500);
and setTimeout(startAction,500);; both had same time and that's why the startAction wasn't executing. I reduced the time of the first function by 100 like that:
$("#fruit1").hide("explode",400);
setTimeout(startAction,500);
It worked!

Why is my function to hide image not working properly?

My code was working properly until I decided to make a small change, and I guess I accidentally deleted something because my console is saying hide image is not defined at decrement when I already defined hide image. I can't find my error everything worked fine :'(. I went over my hide image function and it seems like everything is correct. When I load it on html the error seems to appear when a user does not make a selection is runs the function decrement, so when time reaches zero it displays an image with the correct answer, and it used to clear it out and display the next question with the available choices, but now it just stays on the if time = 0 screen and doesn't move on to the next question.
$(document).ready(function () {
//set up object-array for questions
var trivia = [
{
question: "On Drake & Josh, what's Megan favorite phrase?'",
choices: ["Boobz", "Idiots", "Oh, really?", "Damn! Where are my
apples?"],
rightChoice: 0,
image: "assets/images/boobs.gif",
background: "<img src='assets/images/90back.jpg'>"
},
{
question: "What color lipstick does Spongebob use when he kisses
Mr. Krabs fake Millionth dollar?",
choices: ["Magenta", "Stardust", "Coral Blue #Oof", "Blorange"],
rightChoice: 2,
image: "assets/images/spongebob-coral-blue.gif",
background: "<img src='assets/images/90cart.jpg'>"
},
{
question: "What thottie accessory was popular in the 90's, that
is currently popular today?",
choices: ["chokers", "bandaids", "airpods", "tidepods"],
rightChoice: 0,
image: "assets/images/chokers.gif",
background: "<img src='assets/images/90back.jpg'>"
},
{
question: "During sleepovers, Mystery Date allowed girls to date
which sexy actor?",
choices: ["Port", "James Franco", "Paul Rudd", "Chris Evans, Mr.
America"],
rightChoice: 3,
image: "assets/images/chris-evans.gif",
background: "<img src='assets/images/90cart.jpg'>"
},
{
question: "What was the SPICIEST band in the 90's?",
choices: ["Madonna", "Hillary Clinton", "BackStreet Boyz", "The
Spice Girls"],
rightChoice: 3,
image: "assets/images/zig-a-zig-ha.gif",
background: "<img src='assets/images/90back.jpg'>"
}
];
var rightAnswer = 0;
var wrongAnswer = 0;
var unansweredCount = 0;
var time = 15;
var intervalId;
var userSelection = "";
var selected = false;
var running = false;
var totalCount = trivia.length;
var chosenOne;
var triviaRand;
var newArray = [];
var placeHolder = [];
//hide resetBtn until called
$("#resetBtn").hide();
//click startBtn button to start game
$("#startBtn").on("click", function () {
$(this).hide();
displayTrivia();
runTime();
for (var i = 0; i < trivia.length; i++) {
placeHolder.push(trivia[i]);
};
})
//time: run
function runTime() {
if (!running) {
intervalId = setInterval(decrement, 1000);
running = true;
}
}
//time--
function decrement() {
$("#timeLeft").html("<h4>πŸ‘» Madonna, we're running out of time πŸ‘» "
+ time + " πŸ‘€</h4>");
time--;
//stop time if reach 0
if (time === 0) {
unansweredCount++;
stop();
$("#choicesDiv").html("<p>Oh no! You ran out of time πŸ˜‚. The
correct choice is: " + chosenOne.choices[chosenOne.rightChoice] + "
</p>");
hideimage();
}
}
//time stop
function stop() {
running = false;
clearInterval(intervalId);
}
play question and loop though and display possible answers
function displayTrivia() {
//generate random triviaRand in array
triviaRand = Math.floor(Math.random() * trivia.length);
//console.log(triviaRand);
chosenOne = trivia[triviaRand];
console.log(chosenOne);
$("#questionDiv").html("<h2>" + chosenOne.question + "</h2>");
for (var i = 0; i < chosenOne.choices.length; i++) {
var newUserChoice = $("<div>");
newUserChoice.addClass("answerChoices");
newUserChoice.html(chosenOne.choices[i]);
//assign array position to it so can check rightChoice
newUserChoice.attr("userChoices", i);
$("#choicesDiv").append(newUserChoice);
}
//click function to select rightChoice
$(".answerChoices").click(function () {
//parseInt() function parses a string argument and returns an
integer of the specified radix
//locate array based on userChoice
userSelection = parseInt($(this).attr("userChoices"));
console.log(userSelection);
if (userSelection === chosenOne.rightChoice) {
console.log(chosenOne.choices[chosenOne.rightChoice]);
stop();
selected = true;
rightAnswer++;
userSelection = "";
$("#choicesDiv").html("<p>Damn, boi πŸ±β€πŸ‰πŸ‘Œ</p>");
hideimage();
console.log(rightAnswer);
} else {
stop();
selected = true;
wrongAnswer++;
userSelection = "";
$("#choicesDiv").html("<p>πŸ€”That is incorrect! The correct
choice is: " + chosenOne.choices[chosenOne.rightChoice] + "</p>");
hideimage();
console.log(wrongAnswer);
}
})
function hideimage() {
$("#choicesDiv").append("<img src=" + chosenOne.image + ">");
newArray.push(chosenOne);
trivia.splice(triviaRand, 1);
var hideimg = setTimeout(function () {
$("#choicesDiv").empty();
time = 15;
//run the score screen if all questions answered
if ((wrongAnswer + rightAnswer + unansweredCount) ===
totalCount) {
//clearbck();
$("#questionDiv").empty();
$("#questionDiv").html("<h3>🧐 Game Over! Let's see
your score 😱: </h3>");
$("#choicesDiv").append("<h4> πŸ€ͺ Correct: " +
rightAnswer + "</h4>");
$("#choicesDiv").append("<h4> 🀬 Incorrect: " +
wrongAnswer + "</h4>");
$("#choicesDiv").append("<h4> 🀯 Unanswered: " +
unansweredCount + "</h4>");
$("#resetBtn").show();
rightAnswer = 0;
wrongAnswer = 0;
unansweredCount = 0;
} else {
runTime();
displayTrivia();
}
}, 2000);
}
$("#resetBtn").on("click", function () {
$(this).hide();
$("#choicesDiv").empty();
$("#questionDiv").empty();
for (var i = 0; i < placeHolder.length; i++) {
trivia.push(placeHolder[i]);
}
runTime();
displayTrivia();
})
}
})`
Just as a syntax error correction! You should use single or double quotation in src attribute of img tag in hideimage function:
$("#choicesDiv").append("<img src=' " + chosenOne.image + " '>");

Javascript - changing widths of images

I'm creating a tug of war website as a small project. My problem is that my javascript doesn't seem to want to work.
<script>
function randomTeam(){
var TeamV = Math.floor((Math.random() *2 ) + 1)
document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
return TeamV;
}
function changeWidth(TeamV){
var MetreLeftV = document.getElementById('MetreLeft');
var MetreRightV = document.getElementById('MetreRight');
if(TeamV == 1){
MetreLeftV.style.width += '10px';
MetreRightV.style.width -= '10px';
}
else if(TeamV == 2){
MetreRightV.style.width += '10px';
MetreLeftV.style.width -= '10px';
}
}
</script>
Basically, when the page is loaded the randomTeam function is called, and when the button is pressed, it increments the size of your teams side, and decrements the side of the enemy's team. The problem is, it doesn't work at all. Could anyone help me see where this is going wrong? Thank you in advance :')
You can not just add 10px to the width. Convert the width to a number, add 10, than add px to it.
MetreLeftV.style.width = (parseFloat(MetreLeftV.style.width) + 10) + "px"
Do the same for the others and you will need a check for negative numbers.
function randomTeam() {
var TeamV = Math.floor((Math.random() * 2) + 1)
document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
return TeamV;
}
function changeWidth(TeamV) {
var MetreLeftV = document.getElementById('MetreLeft');
var MetreRightV = document.getElementById('MetreRight');
console.log(parseFloat(MetreLeftV.style.width) + 10 + 'px')
if (TeamV == 1) {
MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) + 10 + 'px';
MetreRightV.style.width = parseFloat(MetreRightV.style.width) - 10 + 'px';
} else if (TeamV == 2) {
MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) - 10 + 'px';
MetreRightV.style.width = parseFloat(MetreRightV.style.width) + 10 + 'px'
}
}
window.setInterval( function () {
var move = randomTeam();
changeWidth(move);
}, 1000);
#MetreLeft {
background-color: red
}
#MetreRight {
background-color: yellow
}
<div id="TeamHeader"></div>
<div id="MetreLeft" style="width:200px">Left</div>
<div id="MetreRight" style="width:200px">Right</div>

DIV animation and property change

I'm trying to simulate TCP packet transmission and sliding window, and fortunately I've made much progress. But now I want to fix a minor issue with the sliding window, which is a sliding DIV:
Hopefully if you are familiar with TCP's slow start, the window size double up to a number, and then increments by one. This is working. Now what I want to fix is sliding to right. So I want to automatically slide one step right when each ack is received at the original machine. Currently it does not move when the ack is received; so each time I press the button, it retransmits many of the previous packets! My work is here: http://web.engr.illinois.edu/~shossen2/CS438/Project/
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
var ssth= $("#ssth").val();
var window_left=0;
for (var i = 1; i <= 32; i++) {
$('#table').append("<div class='inline' id='"+i+"'>"+i+"</div>");
}
document.getElementById(1).style.width = 22;
$("button").click(function() {
if (items < ssth) {
if (items == 0)
items = 1;
else
items = items * 2;
count++;
} else {
items = items + 1;
}
window_left += 20;
window_width=items * 20;
document.getElementById("window_size").innerHTML = items;
document.getElementById("window").style.left= window_left + "px";
document.getElementById("window").style.width=window_width + "px";
speed = +$("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + (parseInt(packetNumber) + parseInt(window_left/20) -1) + "</font>").appendTo(div);
packetNumber++;
div.css({
left: left
/* opacity: 0*/
}).fadeOut(0);
//div.hide();
//left += 20;
}
}
function animateDivs() {
$(".t").each(function (index) { // added the index parameter
var packet = $(this);
packet
.delay(index * 200)
.fadeIn(200, function() {
$('#table #' + (index + window_left/20)).css({background:'yellow'});
})
.animate({left: '+=230px'}, speed)
.animate({left: '+=230px'}, speed)
.fadeOut(200, function () {
packet
.css({
top: '+=20px',
backgroundColor: "#f09090"
})
.text('a' + packet.text());
})
.delay(500)
.fadeIn(200)
.animate({left:'-=230px'}, speed)
.animate({left:'-=230px'}, speed)
.fadeOut(200, function () {
packet
.css({
top: '-=20px',
backgroundColor: "#90f090"
});
$('#table #' + (index + window_left/20)).css({background:'lightgreen'});
});
}).promise().done(function(){
$(".packets").empty();
});
}
});

Categories