<html>
<head>
<script>
var seconds=3600;
function secondPassed() {
var minutes = Math.round((seconds-30)/60);
console.log(minutes);
var hours=Math.round((minutes)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML =hours + ":"+ minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(myVar);
document.getElementById('countdown').innerHTML = "Time Out";
} else {
seconds--;
}
}
var myVar = setInterval(secondPassed ,1000);
</script>
</head>
<body>
<p id="countdown"></p>
</body>
</html>
MY Question : page refresh and countdown timer does not continue.
You can do this by using javascript cookies only but you need to use two file
first file contains total time you need for countdown i.e in your code is 3600 seconds
let us take first file index.html write code
<!DOCTYPE html>
<html>
<head>
<title>Countdown timer</title>
<script type="text/javascript">
var seconds = 3600;
document.cookie = "timer=" + seconds;
window.location.href = "time.html";
</script>
</head>
<body>
</body>
</html>
Next second file let us take time.html add below code
<html>
<head>
<script>
function getCookie(name) {
var nameEQ = name + "=";
//alert(document.cookie);
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(nameEQ) != -1) return c.substring(nameEQ.length,c.length);
}
return null;
}
// var seconds=7200;
// document.cookie = "timer=" + seconds;
function secondPassed() {
seconds = parseInt(getCookie('timer'));
console.log(seconds);
var minutes = parseInt(seconds / 60, 10);
console.log(minutes);
var remainingSeconds = parseInt(seconds % 60, 10);
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds + ' minutes remaning';
if (seconds == 0) {
clearInterval(myVar);
document.getElementById('countdown').innerHTML = "Time Out";
} else {
seconds--;
}
document.cookie = "timer=" + (seconds);
}
var myVar = setInterval(secondPassed ,1000);
</script>
</head>
<body>
<p id="countdown"></p>
</body>
</html>
Note : whenever you want to run countdown timer just run time.html, even if you refresh also, time remains same
Note : if you want to refresh page or want to add when time up add your activity in
if (seconds == 0) {
clearInterval(myVar);
// add activity
}
Related
I made a simple clock and used a button to switch to a stopwatch. Since I couldn't figure out a better solution I duplicated the container, asigned a function that toggles display on/off on the containers to swap between the clock and stopwatch so that it remains in the same position. I don't understand why my stopwatch is not incrementing and what I should do to solve this problem. Any help would be appreciated. Here's my code:
<div id="container">
<div id="clock">
<span id="back">88:88:88</span>
<span id="front">00:00:00</span>
<div class="buttons">
<button id="button-left" onclick="myFunction()"><i class="fas fa-stopwatch"></i></button>
<button id="button-stop"><i class="fa-solid fa-stop"></i></button>
<button id="button-play" ><i class="fa-solid fa-play"></i></button>
<button id="button-right"><i class="fa-solid fa-delete-left"></i></button>
</div>
</div>
</div>
<div id="container-2">
<div id="clock-2">
<span id="back-2">88:88:88</span>
<span id="front-2">00:00:00</span>
<div class="buttons-2">
<button id="button-left-2" onclick="myFunction()"><i class="fas fa-stopwatch"></i></button>
<button id="button-stop-2" onclick="stopSW()"><i class="fa-solid fa-stop"></i></button>
<button id="button-play-2" onclick="startSW()"><i class="fa-solid fa-play"></i></button>
<button id="button-right-2" onclick="reset()"><i class="fa-solid fa-delete-left"></i></button>
</div>
</div>
</div>
function myFunction() {
var x = document.getElementById("container-2");
let y = document.getElementById("container");
if (x.style.display === "none") {
x.style.display = "block";
y.style.display = "none";
} else {
x.style.display = "none";
y.style.display = "block";
}
}
function startSW() {
clearInterval(stopwatch);
start = setInterval(stopwatch, 1000);
}
function stopSW() {
clearInterval(start);
}
function reset(){
clearInterval(stopwatch);
document.getElementById("front-2").innerHTML = "00:00:00";
}
function stopwatch() {
let hours = 0;
let minutes = 0;
let seconds = 0;
let displayHours = 0;
let displayMinutes = 0;
let displaySeconds = 0;
seconds++;
if(seconds == 60){
seconds = 0;
minutes++;
if(minutes == 60) {
minutes = 0;
hours++;
}
}
if (seconds < 10){
displaySeconds = "0" + seconds;
} else {
displaySeconds = seconds;
}
if (minutes < 10){
displayMinutes = "0" + minutes;
} else {
displayMinutes = minutes;
}
if (hours < 10){
displayHours = "0" + hours;
} else {
displayHours = hours;
}
let stopwatchNow = displayHours + ":" + displayMinutes + ":" + displaySeconds;
document.getElementById("front-2").innerHTML = stopwatchNow;
}
Hello at the start of your stopwatch function you set
let hours = 0;
let minutes = 0;
let seconds = 0;
let displayHours = 0;
let displayMinutes = 0;
let displaySeconds = 0;
and that's what you display later in the code, you need to define this variables outside of this function
This is because in function stopwatch, every time this function runs you set
let hours = 0;
let minutes = 0;
let seconds = 0;
let displayHours = 0;
let displayMinutes = 0;
let displaySeconds = 0;
These variables will always be 0, since you set them when function runs. In order to fix this, you need to move them outside the function:
let hours = 0;
let minutes = 0;
let seconds = 0;
let displayHours = 0;
let displayMinutes = 0;
let displaySeconds = 0;
function stopwatch(){
// removed
seconds++; // this stays here
// the rest of your code goes in here
}
This way your variables won't reset to 0 when function starts to run
<div id="container-2">
<div id="clock-2">
<span id="front-2">00:00:00</span>
--- >>
<span id="back-2">88:88:88</span>
</div>
</div>
<div class="buttons-2">
<button id="button-left-2" onclick="myFunction()"><i class="fas fa-stopwatch"></i>fun</button>
<button id="button-stop-2" onclick="stopSW()"><i class="fa-solid fa-stop"></i>stop</button>
<button id="button-play-2" onclick="startSW()"><i class="fa-solid fa-play"></i>start</button>
<button id="button-right-2" onclick="reset()"><i class="fa-solid fa-delete-left"></i>reset</button>
</div>
<script>
function myFunction() {
var node = document.getElementById("back-2");
display(node);
}
var start;
function startSW() {
clearInterval(start);
start = setInterval(stopwatch, 1000);
}
function stopSW() {
clearInterval(start);
}
function reset(){
clearInterval(start);
document.getElementById("front-2").innerHTML = "00:00:00";
document.getElementById("back-2").innerHTML = "00:00:00";
hours = 0;
minutes = 0;
seconds = 0;
}
var hours = 0;
var minutes = 0;
var seconds = 0;
function stopwatch() {console.log('stopwatch')
seconds++;
if(seconds == 60){
seconds = 0;
minutes++;
if(minutes == 60) {
minutes = 0;
hours++;
}
}
display();
}
function display(node){
let displayHours = 0;
let displayMinutes = 0;
let displaySeconds = 0;
if (seconds < 10){
displaySeconds = "0" + seconds;
} else {
displaySeconds = seconds;
}
if (minutes < 10){
displayMinutes = "0" + minutes;
} else {
displayMinutes = minutes;
}
if (hours < 10){
displayHours = "0" + hours;
} else {
displayHours = hours;
}
let stopwatchNow = displayHours + ":" + displayMinutes + ":" + displaySeconds;
if(!node)node=document.getElementById("front-2");
node.innerHTML = stopwatchNow;
}
</script>
there were a variety of mistakes,
clearInterval not being given the correct value
the time variables needed to be declared in global scope
i can only guess what myfunction is supposed to be doing
etc...
have fun
I've been developing a speed test typing game for some time now, and I've been stuck on how to take the time you finish from one HTML page (the game itself) to an alternate one (the score page). I've been trying to use import{} export{}, but I'm not 100% sure how they function and so they haven't exactly worked. I'll attach both the game HTML and Javascript code and the score HTML and Javascript code.
<!-- THIS IS THE HTML PAGE FOR THE GAME -->
<!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Typeboss || Speed Typing Web Game</title>
<link rel="stylesheet" href="../css/gamestyle.css">
<style>
#import url('https://fonts.googleapis.com/css2?family=Cabin:wght#500&display=swap');
</style>
<script src="../js/gamescript.js" defer></script>
<script src="../../main/js/mainscript.js" type="module" defer></script>
<script src="./scorescript.js" type="module" defer></script>
</head>
<body>
<div id="all">
<div id="stats">
<h1 id="bossHealth" class="stat">BOSS HEALTH:</h1>
<h1 id="time" class="stat"><span id="minutes">0</span>:<span id="seconds">00</span></h1>
</div>
<div id="boss">
<img src="../imgs/boss.png" width="400px" height="400px" id="bossSprite">
</div>
<div id="input">
<h3 id="outcome"></h3>
<center><p id="prompt"></p></center>
<textarea id="userInput" name="TypeBox" rows="4" cols="100" autofocus></textarea>
</div>
</div>
</body>
</html>
// THIS IS THE JAVASCRIPT CODE
let scoreTime;
var seconds = 0;
var minutes = 0;
let score = 0;
const userInput = document.getElementById("userInput");
const promptBox = document.getElementById("prompt");
const outcomeText = document.getElementById("outcome");
const bossHealthtText = document.getElementById("bossHealth");
const timer = document.getElementById("time");
const bossSprite = document.getElementById("bossSprite");
const secondsText = document.getElementById("seconds");
const minutesText = document.getElementById("minutes");
let gameActive = true;
document.addEventListener('keypress', function(event){
if (event.key === 'Enter'){
checkInput();
}
});
let bossHealth = 100;
let multiplier = 10;
let mistakes = 0;
//
const prompts = ["How much wood could a woodchuck chuck if a woodchuck could chuck wood?", "I will not lose another pilot.", "I can't find my keys!", "Live as if you were to die tomorrow.", "Toto, I've got a feeling we're not in Kansas anymore...", "May the force be with you.", "If our lives are already written, it would take a courageous man to change the script.", "An apple a day keeps the doctor away.", "Frankly, my dear, I don't give a damn.", "Hello, world!", "My favorite sport is basketball!", "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.", "You only live once, but if you do it right, once is enough.", "I'm the fastest typer in the wild west!", "Frosty the snowman!", "I'm not a big fan of ice cream.", "If birds can fly, then we should too.", "I don't like trucks, they look weird.", "I love typing!", "I'm a rocket man, burning on a fuse out there alone.", "The water was blue and the skies the same, it was summer."];
//GAME INIT
bossHealthtText.innerHTML = `BOSS HEALTH: ${bossHealth}`;
function getNewPrompt() {
promptChoice = Math.floor(Math.random() * prompts.length);
let previousPrompt = prompts[promptChoice];
if (previousPrompt === prompts[promptChoice]){
promptChoice = Math.floor(Math.random() * prompts.length);
console.log("COPY OFF");
}
promptBox.innerHTML = prompts[promptChoice];
}
function checkInput(){
if (userInput.value.trim() === promptBox.innerHTML.trim()){
outcome.innerHTML = "Correct";
bossHealth -= 10;
bossHealthtText.innerHTML = `BOSS HEALTH: ${bossHealth}`;
let hitSprite = Math.floor(Math.random() *2);
if(hitSprite === 0){
bossSprite.src = "../imgs/bosshit/bosshit1.png";
}
if(hitSprite === 1){
bossSprite.src = "../imgs/bosshit/bosshit2.png";
}
setTimeout(function(){
bossSprite.src = "../imgs/boss.png";
}, 1000);
if (bossHealth <= 0){
console.log("WORKING");
window.location.href = "./score.html";
createScore();
}
getNewPrompt();
userInput.value = null;
}
else{
outcome.innerHTML = "Try again...";
userInput.value = null;
multiplier --;
mistakes ++;
return;
}
}
function gameTimer(){
console.log("working");
setTimeout(function(){
setInterval(function(){
seconds++;
if(seconds === 60){
minutes ++;
seconds = 0;
}
if (seconds < 9){
secondsText.innerHTML = "0" + seconds;
}
if (seconds > 9){
secondsText.innerHTML = seconds;
}
if(minutes < 9){
minutesText.innerHTML = minutes;
}
if(minutes > 9){
minutesText.innerHTML = minutes;
}
if (seconds < 9){
scoreTime = minutes + ":" + "0" + seconds;
}
if (seconds > 9){
scoreTime = minutes + ":" + seconds;
}
timePoints = minutes + seconds * 2;
return scoreTime;
return timePoints;
}, 1000)
}, 1000);
}
function game(){
gameTimer();
getNewPrompt();
createHeart();
}
function createScore(){
let bonus = Math.floor(Math.random() * 500);
score = timePoints * multiplier + bonus;
export { score };
}
game();
<!-- THIS IS THE SCORE HTML PAGE -->
<!DOCTYPE html>
<!DOCTYPE html>
<html onclick="celebrate()">
<head>
<meta charset="utf-8">
<title>Typeboss || Your Score!</title>
<link rel="stylesheet" href="../css/scorestyle.css">
<style>
#import url('https://fonts.googleapis.com/css2?family=Cabin:wght#500&display=swap');
</style>
</head>
<body>
<center><h1 style="color: whitesmoke;" id="header">YOU BEAT THE BOSS!</h1></center>
<center><p>(CLICK FOR VICTORY MUSIC)</p></center>
<h3 id="time">TIME:</h3>
<p id="playertime"></p>
<h3 id="score">SCORE:</h3>
<p id="playertime"></p>
<h3 id="mistakes">MISTAKES:</h3>
<p id="playertime"></p>
<h2 id="highscore"></h2>
<button id="redirect">BACK TO HOME</button>
</body>
<script type="module" src="../js/gamescript.js" defer></script>
</html>
// AND HERE IS THE SCORE'S CODE
winMusic = new Audio();
winMusic.src = "./winmusic.mp3";
function celebrate(){
winMusic.play();
winMusic.loop = tru
}
import { score } from "./gamescript.js";
const scoreText = document.getElementById("score");
scoreText.innerHTML = score + " points!"
I hope I can get this issue resolved, and I hope this post was clear enough to understand. This is my first post on stack so please do let me know if I formatted it wrong, and any feedback that could make it easier to understand in the future. Thank you in advance and have a good day.
use cookie for saving variables!
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
You can use Session Storage or for this.
I have 3 prompts, the first is to enter hours and the second minutes, when the user click on button:add n minutes, I would like to display a third prompt by proposing several minutes.
My problem is that my command prompt is executed before the clik on button.
My HTML
<body >
<h1>Exercise 8</h1>
<label>Hours : <input type="text" id='h' /></label>
<label>Minutes : <input type="text" id='m' /></label>
<button id="btn1">Pass 1 minute</button>
<button id="btn2">Add n minutes</button>
<script src="script.js"></script>
</body>
My JS
var hours = parseInt(prompt('Enter your hours please : '));
var minutes = parseInt(prompt('Enter your minutes please : '));
var btnPassOneMinute = document.getElementById('btn1');
var btnPass_N_Minute = document.getElementById('btn2');
/*if (hours != null) {
main();
}*/
btnPassOneMinute.addEventListener('click', addOneMinute);
btnPass_N_Minute.addEventListener('click', add_N_Minute);
main();
addOneMinute();
add_N_Minute();
function main(){
if(minutes > 59){
minutes = 0;
hours += 1;
}
if(hours > 23){
hours = 0;
}
document.getElementById('h').value = hours;
document.getElementById('m').value = minutes;
}
function addOneMinute(){
main();
minutes += 1;
}
function add_N_Minute(){
//main();
var addMinute = parseInt(prompt('Add your minutes : '));
minutes += addMinute;
if(addMinute > 59){
minutes = 0;
}
if(minutes > 59){
minutes = 0;
hours += 1;
}
if(hours > 23){
hours = 0;
}
document.getElementById('h').value = hours;
document.getElementById('m').value = minutes;
}
var hours = parseInt(prompt('Enter your hours please : '));
var minutes = parseInt(prompt('Enter your minutes please : '));
var btnPassOneMinute = document.getElementById('btn1');
var btnPass_N_Minute = document.getElementById('btn2');
/*if (hours != null) {
main();
}*/
btnPassOneMinute.addEventListener('click', addOneMinute);
btnPass_N_Minute.addEventListener('click', add_N_Minute);
main();
addOneMinute();
add_N_Minute();
function main(){
if(minutes > 59){
minutes = 0;
hours += 1;
}
if(hours > 23){
hours = 0;
}
document.getElementById('h').value = hours;
document.getElementById('m').value = minutes;
}
function addOneMinute(){
main();
minutes += 1;
}
function add_N_Minute(){
//main();
var addMinute = parseInt(prompt('Add your minutes : '));
minutes += addMinute;
if(addMinute > 59){
minutes = 0;
}
if(minutes > 59){
minutes = 0;
hours += 1;
}
if(hours > 23){
hours = 0;
}
document.getElementById('h').value = hours;
document.getElementById('m').value = minutes;
}
<!DOCTYPE html>
<html>
<head>
<title>Cours JavaScript</title>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="cours.css">
</head>
<body >
<h1>Exercise 8</h1>
<label>Hours : <input type="text" id='h' /></label>
<label>Minutes : <input type="text" id='m' /></label>
<button id="btn1">Pass 1 minute</button>
<button id="btn2">Add n minutes</button>
<script src="script.js"></script>
</body>
</html>
Thank you...
I have a form for my array of data will print to view with html() and this data each one has child array, I need to get data of those child arrays in my html() as well
Screenshots
my data
how it will look
# Code
HTML
<div class="answerPanel"></div>
<button id="clicks" class="btn btn-primary">Begin</button>
Script
var index = 0;
$("#clicks").click(function(){
// timer function
function timer(seconds, countdownTimer, callback) {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Times Up!";
$("#clicks").attr("disabled", true);
$('.answerPanel').html('<div class="text-center text-danger">OH NO! <br> Times Up!</div>');
} else {
seconds--;
}
//Pass seconds param back to the caller.
callback(seconds);
}
//We pass the countdownTimer param into the timer function as well.
var countdownTimer = null,
seconds = data.quizzes[index].quiz_time;
countdownTimer = setInterval(function() {
timer(seconds, countdownTimer, function(_seconds){
seconds = _seconds;
})
}, 1000);
// printing function
if(typeof data.quizzes[index] != 'undefined'){
var row = `<form>
<div class="row">
<div class="col-md-12">
<div class="pull-left questionTitle">
${data.quizzes[index].question}
</div>
<div class="pull-right" id="countdown"></div>
</div>
<div class="col-md-12">
Choice 1
</div>
<div class="col-md-12">
Choice 2
</div>
<div class="col-md-12">
Choice (etc.)
</div>
</div>
</form>`;
$('.answerPanel').html(row);
index++;
}
if(data.quizzes.length > index+1) {
$("#clicks").html("Next");
}
if(data.quizzes.length === index) {
$("#clicks").html("Finish");
}
//end of printing function
});
Any idea?
Please see my code below
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="banner">
<ul id="eventCal">
</ul>
<button id="clicks">Click</button>
<script type="text/javascript">
jQuery(document).ready(function($){
var quizzes = [{title:'title1',choices:[{choice:'choice1'},{choice:'choice2'}]},
{title:'title2',choices:[{choice:'new1'},{choice:'new2'}]},
{title:'title3',choices:[{choice:'demo1'},{choice:'demo2'}]}];
var index = 0;
//console.log(quizzes.length)
$("#clicks").click(function(){
if(typeof quizzes[index] != 'undefined'){
var html = '<li><span>'+quizzes[index].title+'</span></li>';
if(quizzes[index].choices.length > 0){
html+='<li class="choises">';
quizzes[index].choices.forEach((element, index, array) => {
//console.log(element.title);
html+='<ul>';
html+='<li><span>'+element.choice+'</span></li>';
html+='</ul>';
});
html+='</li>';
}
$("#eventCal").html(html);
index++;
}
if(quizzes.length === index)
$("#clicks").html("Finish");
})
});
</script>
</body>
Inside of row, you can get the choices by:
let choices = quizzes[index].choices
This is what happens when I embed the JsFiddle into my website as a result:
http://i.imgur.com/JkDefod.png
What can I do so that my embedded JsFiddle only shows the running program and not the extra text above?
Here is my JsFiddle code:
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = 0;
sec = 0;
}
}
var min1 = "0" + min + "m";
var min2 = min + "m";
var sec1 = "0" + sec + "s";
var sec2 = sec + "s";
document.getElementById("time").innerHTML = (min < 10 ? min1.fontcolor("red") : min2.fontcolor("red")) + ":".fontcolor("red") + (sec < 10 ? sec1.fontcolor("red") : sec2.fontcolor("red"));
};
var sec = 0;
var min = 15;
handler();
setInterval(handler, 1000);
<div id="worked"></div>
<h1 style="text-align: center;"><span style="color: #ff0000;"><strong>Offer Ends In:</strong></span></h1>
<h1 id="time" style="text-align: center;"> </h1>
You can directly add this code in your page, or using the JsFiddle embeded, do like this:
<div class="someClass">
<script async src="//jsfiddle.net/DiogoBernardelli/vuc85mok/embed/result/"></script>
</div>
And add this in your Stylesheet (.css) file:
.someClass iframe {
height: 200px //you can manually change this height
}
If you want to add only this countdown timer on your web-page, why don't you add your JS code in the tags after your divs?
Something like this:
<body>
<div id="worked"></div>
<h1 style="text-align: center;"><span style="color: #ff0000;"><strong>Offer Ends In:</strong></span></h1>
<h1 id="time" style="text-align: center;"> </h1>
</body>
<script>
var handler = function() {
if (--sec < 0) {
sec = 59;
if (--min < 0) {
min = 0;
sec = 0;
}
}
var min1 = "0" + min + "m";
var min2 = min + "m";
var sec1 = "0" + sec + "s";
var sec2 = sec + "s";
document.getElementById("time").innerHTML = (min < 10 ? min1.fontcolor("red") : min2.fontcolor("red")) + ":".fontcolor("red") + (sec < 10 ? sec1.fontcolor("red") : sec2.fontcolor("red"));
};
var sec = 0;
var min = 15;
handler();
setInterval(handler, 1000);
</script>