So I have a running counter which counts from 0 to 20.000.
But what I would like to have is when a user presses a button, the timer goes back by 250.
So for example, the timer is at 350, it should go back to 100.
I tried the following code:
My timer:
var num = 0;
var max = 20000;
function resourcesCounter() {
if (num > max) {
window.clearTimeout ("tim");
}
else {
document.getElementById('wood').innerHTML = num;
document.getElementById('iron').innerHTML = num;
document.getElementById('clay').innerHTML = num;
num ++;
var tim = window.setTimeout("resourcesCounter()", 100);
}
}
resourcesCounter();
When button is pressed go back 250:
if(buildingLevel == 'Level 1' && building == 'mainBuilding') {
if(wood >= 250 && iron >= 150 && clay >= 200) {
document.getElementById('level-1').innerHTML = 'Level 2';
document.getElementById('wood').innerHTML = wood - 250;
} else {
console.log('Not enough resources');
console.log(wood + ' ' + iron + ' ' + clay);
}
}
However, this code does not work. It changes the countdown for a split second and then goes back to its original values.
I have implemented your functionality in this fiddle. Please see if it works for you:
function startTimer(){
return setInterval(function(){
var counter = document.getElementById("counter-container");
var count = parseInt(counter.textContent.trim());
count += 1;
counter.textContent = count;
}, 100);
};
var timer = startTimer();
var resetButton = document.getElementById('reset-by-250');;
resetButton.addEventListener("click", function(){
clearInterval(timer);
var counter = document.getElementById("counter-container");
var count = parseInt(counter.textContent.trim());
count -= 250;
if(count < 0){
count = 0;
}
counter.textContent = count;
timer = startTimer();
});
var num = 0;
var max = 20000;
function resourcesCounter() {
if (num > max) {
window.clearTimeout ("tim");
}
else {
document.getElementById('wood').innerHTML = num;
document.getElementById('iron').innerHTML = num;
document.getElementById('clay').innerHTML = num;
num ++;
var tim = window.setTimeout("resourcesCounter()", 100);
}
}
function clickbtn(){
num=num-250;
}
<button onclick="clickbtn()">button</button>
You are never setting num when the button is pressed. It will be used when resourcesCounter is called again.
if(buildingLevel == 'Level 1' && building == 'mainBuilding') {
if(wood >= 250 && iron >= 150 && clay >= 200) {
document.getElementById('level-1').innerHTML = 'Level 2';
// Change num so resourcesCounter() will have the updated value
num -= 250;
document.getElementById('wood').innerHTML = num;
} else {
console.log('Not enough resources');
console.log(wood + ' ' + iron + ' ' + clay);
}
}
Related
I have very little to no knowledge when it comes to using JavaScript. I have 24 of the same image given an id from q1 - q24. my code allows for the 24 images to be changed to image2 one at a time, but I need for it to stop and display a text/alert when image2 is clicked.
<script>
{
let num = 1;
function sequence()
{
let back = 1;
while (back < 25)
{
if(back == 1)
{
document.getElementById("q24").src = "question.jpg";
}
else
{
document.getElementById("q" + (back-1)).src = "question.jpg";
}
back++
}
document.getElementById("q" + num).src = "question2.png";
num = num + 1;
if(num > 24){num = 1;}
}
setInterval(sequence, 500);
}
</script>
Save the interval timer to a variable. Then add a click listener to all the images that stops the timer if the current image is the one showing question2.jpg.
{
let num = 1;
for (let i = 1; i <= 24; i++) {
document.getElementById(`q${i}`).addEventListener("click", function() {
if (i == num) {
clearInterval(interval);
}
});
}
let interval = setInterval(sequence, 500);
function sequence() {
for (let i = 1; i <= 24; i++) {
if (i == num) {
document.getElementById(`q${i}`).src = "question2.jpg";
} else {
document.getElementById(`q${i}`).src = "question.jpg";
}
num = num + 1;
if (num > 24) {
num = 1;
}
}
}
}
While I don't fully understand your use case, you could create a click event listener on the document and check the target's src in it.
document.addEventListener('click', function(e) {
if (e.target.src === 'question2.png') {
alert('Clicked question 2');
}
});
all the code was given by the teacher and you just had to place it in the right spot. even working with the teacher we couldn't get it to update the "value" attribute in between turns. it updates at the finish of the game but not during? what are we not seeing? any help appreciated.. if you need to see html i can add as comment
"use strict";
var $ = function(id) { return document.getElementById(id); };
var getRandomNumber = function(max) {
var random;
if (!isNaN(max)) {
random = Math.random(); //value >= 0.0 and < 1.0
random = Math.floor(random * max); //value is an integer between 0 and max - 1
random = random + 1; //value is an integer between 1 and max
}
return random;
};
var playGame = function() {
var odd = 0;
var even = 0;
var player, computer, total;
resetFields(); // clear any previous entries
while (odd < 50 && even < 50) {
//get computers fingers
computer = getRandomNumber(5);
// get player's fingers
player = parseInt(prompt("Enter a number between 1 and 5, or 999 to quit", 999));
if (!isNaN(player) && player <= 5) {
// show current round
$("player").value = player;
$("computer").value = computer;
// update totals
total = player + computer;
if (total % 2 === 0) {
even = even + total;
$("even").value = even;
} else {
odd = odd + total;
$("odd").value = odd;
}
}
//if loop for player quitting
if (player === 999) {
resetFields();
break;
}
}
//after loop ends, determine winner
if (odd >= 50) { $("message").firstChild.nodeValue = "You WIN!"; }
else if (even >= 50) { $("message").firstChild.nodeValue = "You lose :("; }
else { $("message").firstChild.nodeValue = "You quit"; }
// set focus on button so you can play again
$("play").focus();
};
var resetFields = function() {
$("player").value = "0";
$("computer").value = "0";
$("odd").value = "0";
$("even").value = "0";
$("message").firstChild.nodeValue = "";
};
window.onload = function() {
$("play").onclick = playGame;
$("play").focus();
};
I made a little typing game that reveals some random text and you have to type the same in, so that you can test your typing speed. the users has the ability to play again and again, the issue is that when the user types play again, the stopwatch does not begin as it did the first time.
Can anyone help me with making the stopwatch restart everytime the user clicks on the play again button?
[ full code is here] (https://jsfiddle.net/kisho/ncbxd9o4/#&togetherjs=qD5bT8vLiw)
js portion-
const textDisplay = document.querySelector('#text-display');
const input = document.querySelector('#input');
const btn = document.querySelector('#btn');
const textBox = document.querySelector('#text-box');
const countdown = document.querySelector('#countdown');
const stopwatch = document.querySelector('#stopwatch');
const successMessege = document.querySelector('#success-messege');
const stopwatchTime = document.querySelector('#stopwatch-time');
btn.addEventListener('click', runGame);
function runGame() {
if ((btn.innerText = 'Play again')) {
playAgain();
fetchQuote();
countownTimer();
confirmQuote();
} else {
fetchQuote();
countownTimer();
confirmQuote();
}
}
function fetchQuote() {
fetch('https://api.quotable.io/random')
.then((res) => {
return res.json();
})
.then((data) => {
textDisplay.innerText = data.content;
});
}
function countownTimer() {
if (timer !== undefined) {
clearInterval(timer);
}
var timeleft = 2;
var downloadTimer = setInterval(function() {
if (timeleft <= 0) {
clearInterval(downloadTimer);
document.getElementById('countdown').innerHTML = 'Start Typing!';
input.classList.remove('displayNone');
runningStopwatch.classList.remove('displayNone');
begin();
} else {
document.getElementById('countdown').innerHTML = timeleft + ' seconds remaining';
}
timeleft -= 1;
}, 1000);
}
function confirmQuote() {
if ((countdown.innerHTML = 'Start typing!')) {
input.addEventListener('keyup', function(event) {
if (event.keyCode === 13) {
if (textDisplay.innerText === input.value) {
btn.innerText = 'Play again';
// textBox.classList.add('displayNone');
hold();
} else successMessege.innerText = 'Missed something there, try again!!';
}
});
}
}
function playAgain() {
textBox.classList.remove('displayNone');
input.classList.add('displayNone');
input;
input.value = '';
successMessege.innerText = '';
}
let ms = 0,
s = 0,
m = 0;
let timer;
let runningStopwatch = document.querySelector('.running-stopwatch');
function begin() {
timer = setInterval(run, 10);
}
function run() {
runningStopwatch.textContent =
(m < 10 ? '0' + m : m) + ': ' + (s < 10 ? '0' + s : s) + ': ' + (ms < 10 ? '0' + ms : ms);
ms++;
if (ms == 100) {
ms = 0;
s++;
}
if (s == 60) {
s = 0;
m++;
}
}
function hold() {
clearInterval(timer);
successMessege.innerText = `Nice job! You just typed in x seconds!`;
}
function stop() {
(ms = 0), (s = 0), (m = 0);
runningStopwatch.textContent =
(m < 10 ? '0' + m : m) + ': ' + (s < 10 ? '0' + s : s) + ': ' + (ms < 10 ? '0' + ms : ms);
}
You are not handling the clearInterval correctly.
You are clearing the interval only if one ends the game successfully.
My solution would be:
When calling the countownTimer() function, the first thing you should do, is to check if the interval timer is still running.
function countownTimer() {
if (timer !== undefined) {
clearInterval(timer);
}
// [...]
}
The next thing would be, to start the interval every time begin() gets called.
function begin() {
timer = setInterval(run, 10);
}
When I clicking the button the user HP goes down till 0 and then button changes. But what happens more is, when the userHealth reaches zero the button did not change. You have to click one more time to button change. How to solve this ?
JS:
$(".attBtn").click(function() {
var userId = 4;
var attackdmg = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
var userdmg = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
var minimum = 0;
if(userHealth == 0){
info.innerHTML = '<strong>'+user.textContent+'</strong> have been defeated.';
attackBtn.css("backgroundColor", "blue");
attackBtn.css("border", "none");
innerAttBtn.innerHTML = "Get the reward <img src="+"/img/chest2.png"+"/> ";
return false;
}else if(attackerHealth == 0){
info.innerHTML = '<strong>You</strong> have been defeated.';
}else if(attackerHealth == 0 && userHealth == 0){
info.innerHTML = '<strong>DRAW FIGHT</strong>';
}else{
userHealth -= attackdmg;
attackerHealth -= userdmg;
document.getElementById('attackerBar').setAttribute("style","width:"+attackerHealth+"%");
document.getElementById('userBar').setAttribute("style","width:"+userHealth+"%");
$.ajax("/arena/fight-user/"+userId+"/attack/"+attackdmg+"/"+userdmg,
{
});
if(userHealth < 0){userHealth = minimum;}
if(attackerHealth < 0){attackerHealth = minimum;}
userHp.innerHTML = '<strong>'+userHealth+'</strong>';
attackerHp.innerHTML = '<strong>'+attackerHealth+'</strong>';
info.innerHTML = '<strong>' +user.textContent+'</strong>' +' hit <strong>You</strong> with ' +userdmg+' dmg <br> ' + '<strong>You</strong> hit '
+'<strong>'+user.textContent+'</strong>'+ ' with '+ attackdmg +' dmg';
}
});
there is a logical flaw.
The reason, why you have to click once more, is because you declare what should happen at 0 HP before the HP gets actually to zero.
The solution
put this
userHealth -= attackdmg;
attackerHealth -= userdmg;
if(userHealth < 0){userHealth = minimum;}
if(attackerHealth < 0){attackerHealth = minimum;}
before this
if(userHealth == 0){
...
I have a typing speed test with a textarea and I have I paragraph split into spans. Every time the user hits space, it highlights the next span. Then I split the textarea val() and compare the two at the end. I have everything working except I cannot get the enter key to do what I want it to do. I need it to act like the space bar(in the background) and act as the enter key on screen.
$(function() {
//APPEARANCE
$('#error').hide();
$('#oldTextOne').hide();
$('#oldTextTwo').hide();
$('#oldTextThree').hide();
$('#oldTextFour').hide();
$('#oldTextFive').hide();
$('.linkBox').hover(function() {
$(this).removeClass('linkBox').addClass('linkHover');
}, function() {
$(this).removeClass('linkHover').addClass('linkBox');
});
//FUNCTIONALITY VARIABLES
var min = '5';
var sec = '00';
var realSec = 0;
var errorTest = "hasn't started yet";
var oldTextVal;
var para;
// PICK A RANDOM PARAGRAPH
function pickRandom() {
var date = new Date();
date = date.getTime();
date += '';
var dateSplit = date.split('');
var temp = dateSplit.length - 1;
var picker = dateSplit[temp];
if (picker === '0' || picker === '1') {
para = $('#oldTextOne').text();
}
else if (picker === '2' || picker === '3') {
para = $('#oldTextTwo').text();
}
else if (picker === '4' || picker === '5') {
para = $('#oldTextThree').text();
}
else if (picker === '6' || picker === '7') {
para = $('#oldTextFour').text();
}
else {
para = $('#oldTextFive').text();
}
var splitPara = para.split(' ');
for (i in splitPara) {
$('#oldTextBox').append('<span id="pw' + i + '">' + splitPara[i] + '</span> ');
}
}
pickRandom();
//FUNCTION FOR TIMER
//APPEARANCE
function show() {
$('#timer').text(min + ' : ' + sec);
}
show();
//COUNT-DOWN
var count = function() {
sec = +sec - 1;
sec += '';
realSec++;
if (+sec === -1) {
sec = '59';
min -= 1;
min += '';
}
if (sec.length === 1) {
sec = '0' + sec;
}
show();
if (sec === '00' && min === '0') {
clearInterval(run);
checkIt();
}
};
// TYPE THE TEXT INTO #TYPEDTEXTBOX
$('#pw0').addClass('green');
var lastLetter;
$('#typedTextBox').focus().keypress(function() {
if (errorTest === "hasn't started yet") {
errorTest = 'running';
run = setInterval(count, 1000);
}
//STOP ERRORS FROM PEOPLE HITTING SPACE BAR TWICE IN A ROW !!NOT WORKING IN IE8
var thisLetter = event.which;
if (lastLetter === 32 && event.which === 32) {
event.preventDefault();
}
lastLetter = thisLetter;
}).keyup(function() {
//STOP ERRORS FROM BACKSPACE NOT REGISTERING WITH KEYPRESS FUNCTION
if (event.which === 8) {
lastLetter = 8;
}
if (event.which === 13) {
?????????????????????????????????????????????
}
//SPLIT THE TYPED WORDS INTO AN ARRAY TO MATCH THE OLD TXT SPANS (TO HIGHLIGHT THE CURRENT WORD IN OLDTXT)
var typedWords = $(this).val().split(' ');
var temp = typedWords.length - 1;
var oldTemp = temp - 1;
var stopErrors = temp + 1;
$('span:nth(' + temp + ')').addClass('green');
$('span:nth(' + oldTemp + ')').removeClass('green');
$('span:nth(' + stopErrors + ')').removeClass('green');
//SCROLL
if (typedWords.length < 50) {
return;
}
else if (typedWords.length > 50 && typedWords.length < 100) {
$('#oldTextBox').scrollTop(30);
}
else if (typedWords.length > 100 && typedWords.length < 150) {
$('#oldTextBox').scrollTop(60);
}
else if (typedWords.length > 150 && typedWords.length < 200) {
$('#oldTextBox').scrollTop(90);
}
else if (typedWords.length > 200) {
$('#oldTextBox').scrollTop(120);
}
//KEEP FOCUS IN THE TYPING AREA
}).blur(function() {
if (errorTest !== 'done') {
$(this).focus();
}
});
//COMPARE
//MAKE AN ARRAY OF THE OLDTEXT
var oldWords = para.split(' ');
//FUNCTION TO DISPLAY RESULTS
var checkIt = function() {
errorTest = 'done';
var correct = 0;
var typed = $('#typedTextBox').val();
var typedWords = typed.split(' ');
$('#typedTextBox').blur();
for (i = 0; i < typedWords.length; i++) {
if (typedWords[i] === oldWords[i]) {
correct += 1;
}
}
var errors = typedWords.length - correct;
var epm = (errors / realSec) * 60;
var wpm = Math.round(( ($('#typedTextBox').val().length / 5 ) / realSec ) * 60);
var realWpm = Math.round(wpm - epm);
//SHOW RESULTS
$('#oldTextBox').html('<br><span id="finalOne">WPM : <strong>' + realWpm + ' </strong></span><span class="small">(error adjusted)</span><br><br><span id="finalTwo">You made ' + errors + ' errors </span><br><span id="finalThree">Total character count of ' + $('#typedTextBox').val().length + '</span><br><span id="finalFour">Gross WPM : ' + wpm + '</span>');
};
//STOP BUTTON APPEARANCE AND FUNCTIONALITY
$('#stop').mouseover(function() {
$(this).addClass('stopHover');
}).mouseout(function() {
$(this).removeClass('stopHover');
}).click(function() {
if (errorTest === 'running') {
checkIt();
clearInterval(run);
errorTest = 'done';
}
});
});
try this:
//ENTER KEY
if (event.which === 13) {
//event.stopPropagation(); or
event.preventDefault();
//simulate spacebar
$(window).trigger({type: 'keypress', which: 32, keyCode: 32});
}
#james - Thanks for the help. I found a better way of thinking about the problem. Instead of changing the enter key action, I changed the split function to var typedWords = typed.split(/[ \r\n]+/);