Javascript/jQuery bug in my Trivia Game - javascript

I am creating a basic Trivia Game for a Web Dev class. We are to use HTML/CSS/JS/jQuery to create it. The new element that we are to work with in this assignment are the setTimeout() & setInterval() methods.
After clicking the start button, the game will ask a question and offer 4 possible answers. The user either clicks an answer or the timer runs out. The results are displayed and then then the next questions auto-loads. Once all of the questions in the questions array are asked, the game displays the overall results and then refreshes screen.
The bug that I discovered is that if I let the timer run all the way down until the "zero" is just displayed on the screen and then quickly click on an answer, it causes the game to react as if the conditions of an answer being clicked and the time running out had occurred simultaneously. Then the next question loads too many answers and the timer is decrementing at an increased rate. I'm not sure if there is some sort of time lag in the timer reaching zero somewhere that allows the answer clicks to transmit through and this creates a new timerID that doesn't get cleared which causes the time decrementing on the next question to increase in rate.
I've created a Fiddle for this: https://jsfiddle.net/brianpatrickhummel/0a2hg782/
var correctAnswers = 0;
var incorrectAnswers = 0;
var unansweredQuestions = 0;
var timeRemaining = 16;
var intervalID;
var indexQandA = 0; //index to load a different question each round without the game reset or screen refresh
var answered = false; //variable to stop the timer if user has clicked an answer
var correct;
var triviaGame = [
{question:"HOW MANY COLORS ARE THERE ON A RUBIK'S CUBE ?", answer:["5", "6", "7", "4"], correct: "1", image:("assets/images/rubik.png")},
{question:"WHAT IS THE SPEED OF LIGHT ?", answer:["8,600 MILES per SECOND","86,000 MILES per SECOND","186,000 MILES per SECOND","886,000 MILES per SECOND"], correct:"2", image:("assets//images/lightspeed.jpg")},
{question:"APPROXIMATELY HOW LONG DOES IT TAKE FOR SUNLIGHT TO REACH THE EARTH ?", answer:["45 SECONDS", "10 HOURS", "2 HOURS 15 MINUTES", "8 MINUTES"], correct:"3", image:("assets//images/sunlight.jpg")},
{question:"WHAT ELEMENT'S CHEMICAL SYMBOL IS Pb ?", answer:["POTASSIUM","STRONTIUM","LEAD","PALLADIUM"], correct:"2", image:("assets//images/periodictable.png")},
{question:"HOW FAST CAN BEES FLY ?", answer:["35 MPH", "15 MPH", "48 MPH", "8 MPH"], correct:"1", image: ("assets/images/bee.png")},
{question:"WHAT IS THE MOST ABUNDANT ELEMENT IN THE UNIVERSE ?", answer:["HYDROGEN", "OXYGEN", "HELIUM", "CARBON"], correct:"0", image:("assets//images/universe.png")},
{question:"THE AIR THAT WE BREATHE IS COMPRISED MOSTLY OF WHAT ELEMENT ?", answer:["CARBON", "ARGON", "OXYGEN", "NITROGEN"], correct:"3", image:("assets//images/breathe.jpg")},
{question:"WHAT IS THE DIAMETER OF THE EARTH ?", answer:["140,000 MILES", "2,500,000 MILES", "8,000 MILES", "25,000,000 MILES"], correct:"2", image:("assets//images/earth.png")}
];
// ------------- FUNCTION DECLARATIONS ----------------------------
function startGame() {
console.log("game has begun");
$('.start-button').remove();
correctAnswers = 0;
incorrectAnswers = 0;
unansweredQuestions = 0;
loadQandA ();
}
function loadQandA() {
// console.log(correctAnswers);
// console.log(incorrectAnswers);
// console.log(unansweredQuestions);
// console.log(indexQandA);
answered = false; // will allow timeRemaining to be pushed back to <h5> after round reset....else statement in function timer()
timeRemaining = 16;
intervalID = setInterval(timer, 1000);
if (answered === false){
timer();
}
correct = triviaGame[indexQandA].correct;
var question = triviaGame[indexQandA].question;
$('.question').html(question);
for (var i = 0; i < 4; i++) {
var answer = triviaGame[indexQandA].answer[i];
$('.answers').append('<h4 class= answersAll id=' + i + '>' + answer + '</h4>');
}
$( "h4" ).click(function() {
var id = $(this).attr('id');
// alert(id);
if (id === correct) {
answered = true; // stops the timer
// alert("correct answer");
$('.question').text("THE ANSWER IS: " + triviaGame[indexQandA].answer[correct]);
correctAnswer ();
}
else {
answered = true; //stops the timer
// alert("incorrect answer");
$('.question').text("YOU CHOSE: " + triviaGame[indexQandA].answer[id] + ".....HOWEVER THE ANSWER IS: " + triviaGame[indexQandA].answer[correct]);
incorrectAnswer();
}
});
}
function timer() {
if (timeRemaining === 0) {
answered = true;
clearInterval(intervalID);
$('.question').text("THE CORRECT ANSWER IS: " + triviaGame[indexQandA].answer[correct]);
unAnswered();
}
else if (answered === true) {
clearInterval(intervalID);
}
else {
timeRemaining--;
$('.timeRemaining').text('YOU HAVE ' + timeRemaining + ' SECONDS TO CHOOSE').removeClass('animated pulse infinite');
}
}
function correctAnswer() {
correctAnswers++;
$('.timeRemaining').text("YOU HAVE ANSWERED CORRECTLY!").css({'color':'#3D414F'}).addClass('animated pulse infinite');
resetRound();
}
function incorrectAnswer() {
incorrectAnswers++;
$('.timeRemaining').text("YOU HAVE ANSWERED INCORRECTLY!").css({'color':'#3D414F'}).addClass('animated pulse infinite');
resetRound();
}
function unAnswered() {
unansweredQuestions++;
$('.timeRemaining').text("YOU FAILED TO CHOOSE AN ANSWER").css({'color':'#3D414F'}).addClass('animated pulse infinite');
resetRound();
}
function resetRound() {
$('.answersAll').remove();
$('.answers').append('<img class=answerImage src="' + triviaGame[indexQandA].image + ' ">'); // adds answer image
indexQandA++; // increments index which will load next question when loadQandA() is called again
if (indexQandA < triviaGame.length) {
setTimeout(function(){ loadQandA(); $('.answerImage').remove();}, 5000); // removes answer image from previous round
}
else {
setTimeout(function(){
$('.question').remove();
$('.timeRemaining').remove();
$('.answerImage').remove();
$('.answers').append('<h4 class= answersAll end>CORRECT ANSWERS: ' + correctAnswers + '</h4>');
$('.answers').append('<h4 class= answersAll end>INCORRECT ANSWERS: ' + incorrectAnswers + '</h4>');
$('.answers').append('<h4 class= answersAll end>UNANSWERED QUESTIONS: ' + unansweredQuestions + '</h4>');
setTimeout(function(){ location.reload(); }, 7000);
}, 5000);
}
}
// ----------------------- MAIN PROCESS ---------------------
$('.startButton').on("click", function() {
$('.startButton').removeClass('infinite').addClass('animated fadeOutDown'); //manages the Animate.css applied to Start Button
startGame();
});

Each time you establish a timer with either setTimeout or setInterval, you need to set a variable to the returned timer id. That variable needs to have a high enough scope so that you can access it from any place where the timer must be interacted with.
Then, anywhere you need to interrupt the timer, you can clear it. In your case, when an answer is clicked, you need to stop the countdown timer.
Here's a scaled down example:
window.addEventListener("DOMContentLoaded", function(){
var clock = document.getElementById("clock");
var btnStart = document.getElementById("btnStart");
var btnStop = document.getElementById("btnStop");
// Declare this where you can get at it
var timer1 = null;
function start(){
clock.textContent = new Date().toLocaleTimeString();
timer1 = setTimeout(start, 900);
}
function stop(){
// Cancel the timer
clearTimeout(timer1);
}
btnStart.addEventListener("click", start);
btnStop.addEventListener("click", stop);
start();
});
<div id="clock"></div>
<button id="btnStop">Stop the Clock</button>
<button id="btnStart">Start the Clock</button>

Related

timer starts automatically instead of on a button press in javascript

I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}

I can't get the timer to display

I cannot get the timer countdown to display at all.
I've tried console logging but idk. I'm a noob.
var game = {
correct: 0,
incorrect: 0,
countdown: 90,
countdown: function () {
game.countdown--;
$("#counter-number").html(game.countdown);
if (game.countdown === 0) {
alert("Out of Time!");
game.done();
console.log(countdown)
}
},
// Can't get counter to stay on screen
start: function () {
timer = setInterval(game.countdown, 1000);
$('#insidecontainer').prepend('<h2>Time Remaining: <span id="counter-number">90</span> Seconds</h2>');
$("#start").remove();
console.log(timer)
for (var i = 0; i < questions.length; i++) {
panel.append('<h2>' + questions[i].question + '</h2>');
for (var j = 0; j < questions[i].choices.length; j++) {
panel.append('<input type="radio" name ="question' + '-' + i + '"value="' + questions[i].choices[j] + '">' + questions[i].choices[j]);
}
}
panel.append("<button id='done'>Done!</button>");
},
The timer comes up as 90 but then disappears after 1 second. I want the timer to display it's counting down until it gets to zero.
The questions is missing a lot of code but there are various ways to implement timer with JS and JS libraries.
Following your approach maybe something like this would be sufficient?
var game = {
correct: 0,
incorrect: 0,
countdownseconds: 90,
intervalId: null,
countdown: function () {
game.countdownseconds--;
if (game.countdownseconds === 0)
clearInterval(game.intervalId);
$("#counter-number").html(game.countdownseconds);
},
start: function () {
$('#insidecontainer').prepend('<h2>Time Remaining: <span id="counter-number">90</span> Seconds</h2>');
game.intervalId = setInterval(game.countdown, 1000);
}
}
game.start();
As jimmy5312 pointed out there was collision with the identifier countdown so I used countdownseconds to hold the seconds.
Using this approach, most of your logic would go to countdown function, but I think you should still be able to to extract another function to handle the business logic for the questions and call it right after $("#counter-number").html(game.countdownseconds);

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 + " '>");

Loading/Buffering text while loading audio in html5 custom player with JavaScript

I found a custom html5 audio player and successfully redesigned it, now I want to add a "loading/buffering" text while player is loading audio (otherwise users may freak out because nothing happening after they hit play).
Here is the code to explain:
function calculateTotalValue(length) {
var minutes = Math.floor(length / 60),
seconds_int = length - minutes * 60,
seconds_str = seconds_int.toString(),
seconds = seconds_str.substr(0, 2),
time = minutes + ':' + seconds
return time;
}
function calculateCurrentValue(currentTime) {
var current_hour = parseInt(currentTime / 3600) % 24,
current_minute = parseInt(currentTime / 60) % 60,
current_seconds_long = currentTime % 60,
current_seconds = current_seconds_long.toFixed(),
current_time = (current_minute < 10 ? "0" + current_minute : current_minute) + ":" + (current_seconds < 10 ? "0" + current_seconds : current_seconds);
return current_time;
}
function initProgressBar() {
var player = document.getElementById('player');
var length = player.duration
var current_time = player.currentTime;
// calculate total length of value
var totalLength = calculateTotalValue(length)
jQuery(".end-time").html(totalLength);
// calculate current value time
var currentTime = calculateCurrentValue(current_time);
jQuery(".start-time").html(currentTime);
var progressbar = document.getElementById('seekObj');
progressbar.value = (player.currentTime / player.duration);
progressbar.addEventListener("click", seek);
if (player.currentTime == player.duration) {
$('#play-btn').removeClass('pause');
}
function seek(evt) {
var percent = evt.offsetX / this.offsetWidth;
player.currentTime = percent * player.duration;
progressbar.value = percent / 100;
}
};
function initPlayers(num) {
// pass num in if there are multiple audio players e.g 'player' + i
for (var i = 0; i < num; i++) {
(function() {
// Variables
// ----------------------------------------------------------
// audio embed object
var playerContainer = document.getElementById('player-container'),
player = document.getElementById('player'),
isPlaying = false,
playBtn = document.getElementById('play-btn');
// Controls Listeners
// ----------------------------------------------------------
if (playBtn != null) {
playBtn.addEventListener('click', function() {
togglePlay()
});
}
// Controls & Sounds Methods
// ----------------------------------------------------------
function togglePlay() {
if (player.paused === false) {
player.pause();
isPlaying = false;
$('#play-btn').removeClass('pause');
} else {
player.play();
$('#play-btn').addClass('pause');
isPlaying = true;
}
}
}());
}
}
initPlayers(jQuery('#player-container').length);
Player code (source) on CodePen
I want some text will be shown in the same "span" that shows
"start time" (please see CodePen) while media is loading;
The text " 'loading.' 'loading..' 'loading...' " must changing on
loop while media is loading;
When it is loaded the "loading" text must be changing on "start
time" as it is now.
So basically I wat to put some text in start time while it is not shows anything but zeroes
I'm new to JS
Thats why I need some help or point to right direction
You can use the "readyState" event of the audio player to show hide loading.
There is already a "SetInterval" even which is getting fired so in that we can add this code to show/hide the "Loading"
1st add the loading element(You can put it where ever you want"
<h3 id="loading" style="display:none;">Loading</h3>
Now let's add the code to check "readystate" inside "SetInterval"
if(player.readyState>0&&player.readyState<4){
$("#loading").show();
}
else{
$("#loading").hide();
}
You can read more about "readystate" here
/As per the request I have changed the code to use the start time as loading, to make it work we don't have to add anything inside html but need to do some changes in JS
First, add this inside "togglePlay" functions pay condition in the "else" block.
$(".start-time").html("Loading...");
After this inside "initProgressBar()" function replace the "jQuery(".start-time").html(currentTime);" with the below code
if (player.readyState === 4) {
jQuery(".start-time").html(currentTime);
}
so how it will work, When you click play button the start time text will show as "Loading" but once the file is loaded and the player is ready to play the text will be changed to "start time", Hope it works. Also updated the CodePen for better understanding
You can find the full code in the CodePen
You could use setInterval to cycle through the different 'loading' text and clearInterval when the player's play promise is done.
Here's a basic example:
var dots = 1;
var loading = setInterval(function(){
dots = (dots % 3) + 1;
$(".start-time").text("Loading" + Array(dots + 1).join("."));
console.log($(".start-time").text());
}, 250);
player.play().then(function() {
clearInterval(loading);
}).catch((error) => {
$(".start-time").text("Error loading");
});

Can you count clicks on a certain frame in an animation in javascript?

I'm looking to build a very simple whack a mole-esque game in javascript. Right now I know how to do everything else except the scoring. My current animation code is as follows
<script language="JavaScript"
type="text/javascript">
var urls;
function animate(pos) {
pos %= urls.length;
document.images["animation"].src=urls[pos];
window.setTimeout("animate(" + (pos + 1) + ");",
500);
}
window.onload = function() {
urls = new Array(
"Frame1.jpg","Frame2.jpg"
);
animate(0);
}
</script>
So far it all works, the first frame is the hole and the second is the groundhog/mole out of the hole. I need to count the clicks on the second frame but I can't figure out how to incorporate a counter. Help? (Sorry if the code doesn't show up correctly, first time using this site)
Here is an example that counts clicks on the flashing animation: http://jsfiddle.net/maniator/TQqJ8/
JS:
function animate(pos) {
pos %= urls.length;
var animation = document.getElementById('animation');
var counter = document.getElementById('counter');
animation.src = urls[pos];
animation.onclick = function() {
counter.innerHTML = parseInt(counter.innerHTML) + 1;
}
setTimeout(function() {
animate(++pos);
}, 500);
}
UPDATE:
Here is a fiddle that only detects click on one of the images: http://jsfiddle.net/maniator/TQqJ8/8/

Categories