how to make to stop on specific number when button clicked - javascript

<html>
<head>
<style>
</style>
</head>
<body>
<label id="minutes">0</label>
<label id="seconds">0</label>
<script type="text/javascript">
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 150);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%10);
}
function pad(val)
{
var valString = val + "";
if(valString.length < 1)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var totalSeconds = 0;
setInterval(setTime, 100);
function setTime()
{
minutesLabel.innerHTML = pad(totalSeconds%6);
}
function pad(val)
{
var valString = val + "";
if(valString.length < 1)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<script>
function myFunction1() {
var a = document.getElementById("minutes");
var b = document.getElementById("seconds");
dont' know what should i write in here
</script>
<button onclick="myFuntion1">click</button>
</body>
<html>
i wanna make stop button in specific number.
so whenever you clicked the button
the countup stop on 15.
any help will be so appreciated. :)
thanks
--repeat cause it said i can't upload this question because of not enough detail.
i wanna make stop button in specific number.
so whenever you clicked the button
the countup stop on 15.
any help will be so appreciated. :)
thanks

Print out the 1 and 5.
Stop the timer. (You should assign a variable to each timer first)
<html>
<head>
<style>
</style>
</head>
<body>
<label id="minutes">0</label>
<label id="seconds">0</label>
<script type="text/javascript">
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
var t1 = setInterval(setTime, 150);
function setTime()
{
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds%10);
}
function pad(val)
{
var valString = val + "";
if(valString.length < 1)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<script type="text/javascript">
var minutesLabel = document.getElementById("minutes");
var totalSeconds = 0;
var t2 = setInterval(setTime, 100);
function setTime()
{
minutesLabel.innerHTML = pad(totalSeconds%6);
}
function pad(val)
{
var valString = val + "";
if(valString.length < 1)
{
return "0" + valString;
}
else
{
return valString;
}
}
</script>
<script>
function myFunction1() {
document.getElementById("minutes").innerHTML = '1';
document.getElementById("seconds").innerHTML = '5';
clearInterval(t1);
clearInterval(t2);
}
</script>
<button onclick="myFunction1()">click</button>
</body>
<html>

Related

Need help sharing a Javascript variable locally between files

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.

how to calculate the time keydown to keyup

this is the code, but it's not work,where is wrong.
<input type="text" name ="name" place="">
<button disabled="disabled">click</button>
<script>
$(function(){
var i = 0;
$('input').keydown(function(event) {
i++;
var temp = i;
setTimeout(function(){
var rate = (i-temp);
console.log(rate);
if(rate--){
$('button').attr('disabled',true);
}else{
$('button').attr('disabled',false);
}
},1000)
});
});
thx so much for you guys help
You can use JavaScript storage which is similar to session variables:
<script>
window.onload = function () {
document.onkeydown=(function (event) {
if (localStorage["Count"] == null) {
localStorage["Count"] = 0;
}
else {
localStorage["Count"]++;
}
alert("The count is: " + localStorage["Count"]);
});
}
</script>
in jquery you can use the following code :
KeyDown :
$("input").keydown(function(){ // when user push the key
// do something !!
});
KeyUp :
$("input").keyup(function(){ // when user is not pushing key enymore
// do something !!
});
Calculate time between keydown and keyup:
timebetween = 0;
var count = null;
$("input").keydown(function(){
timebetween = 0;
count = setInterval(function(){
timebetween++;
}, 1);
});
$("input").keyup(function(){
clearInterval(count);
$("body").append("<br>Time between keydown and keyup is "+timebetween+"ms");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
You can try this it will give you time in miliseconds.
$(document).ready(function(){
var startTime = false, endTime;
$(window).keypress(function(){
if(!startTime){
startTime = $.now();
}
});
$(window).keyup(function(){
endTime = $.now();
var keyPressedTime = (endTime - startTime);
console.info('keyyyUpppp', keyPressedTime)
startTime = false;
});
});
you can use this :
<!DOCTYPE HTML>
<html>
<head>
<title>Js Project</title>
</head>
<body>
<input type="text" id="txt" />
<div id="label"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var time = 0; // pressing time
var pressed = 0; // key is pushed or not ?
var timer = setInterval(calculate, 10); // calculate time
$("#txt").keydown(function(){
pressed = 1;
});
$("#txt").keyup(function(){
pressed = 0;
$("#label").html("Pressing Time : "+time+" ms");
time = 0
});
function calculate() { // increase pressing time if key is pressed !!
if (pressed == 1) {
time += 1;
}
}
</script>
</body>
</html>

Timer not accurate [duplicate]

This question already has answers here:
How to create an accurate timer in javascript?
(15 answers)
Closed 6 years ago.
I am building an activity timer, but the code I have is not working properly. The timer is going ~40% faster than real time. What's going wrong?
var sec = 00;
var min = 00;
var hr = 00;
var t;
var timer_is_on = 0;
function timedCount() {
if (min == 0) {
min = 1;
}
document.getElementById('seconds').value = sec;
document.getElementById('minutes').value = min;
$('.node-form .form-item:nth-child(4) input').val(min);
document.getElementById('hours').value = hr;
$('.node-form .form-item:nth-child(3) input').val(hr);
sec = sec + 1;
if (sec == 60) {
sec = 0;
min = min + 1;
if (min == 60) {
min = 1;
hr = hr + 1;
}
}
t = setTimeout("timedCount()", 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
function resetCount() {
stopCount();
sec = 0;
min = 0;
hr = 0;
document.getElementById('hours').value = 00;
$('.node-form .form-item:nth-child(3) input').val('0');
document.getElementById('minutes').value = 00;
$('.node-form .form-item:nth-child(4) input').val('0');
document.getElementById('seconds').value = 00;
}
function putInTimelog() {
// Put hours
var hourItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-hours-0-value-", 0) === 0) {
hourItems.push(hourFields[i]);
}
}
var hourField = 'edit-field-timelog-hours-0-value-';
hourField = hourField.concat(hourItems.length);
document.getElementById(hourField).value = hr;
// Put minutes
var minuteItems = [];
var hourFields = document.getElementById("node-form").getElementsByTagName("input");
for (var i = 0; i < hourFields.length; i++) {
//omitting undefined null check for brevity
if (hourFields[i].id.lastIndexOf("edit-field-timelog-minutes-0-value-", 0) === 0) {
minuteItems.push(hourFields[i]);
}
}
var minuteField = 'edit-field-timelog-minutes-0-value-';
minuteField = minuteField.concat(minuteItems.length);
alert(minuteField);
alert((minuteField).length);
document.getElementById(minuteField).value = min;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<span class="timer-title"><strong>Activity timer</strong></span>h:
<input id="hours" readonly="readonly" size="2" type="text" /> m:
<input id="minutes" readonly="readonly" size="2" type="text" /> s:
<input id="seconds" readonly="readonly" size="2" type="text" /><span class="timer-buttons"><input onclick="doTimer()" type="button" value="Start" /> <input onclick="stopCount()" type="button" value="Stop" /> <input onclick="resetCount()" type="button" value="Reset" /> </span>
</form>
View on JSFiddle
clock.js is my repo that might help when used in conjunction with window.setInterval(). Working example included.
Add <script src="https://rack.pub/clock.min.js"></script> to your HTML then call clock.now --> 1462248501241 each time you want a time snapshot. You can add and subtract intuitively from there.
The actual js looks like:
var clock = (function() {
// object to expose as public properties and methods such as clock.now
var pub = {};
//clock.now
Object.defineProperty(pub, "now", {
get: function () {
return Date.now();
}
});
//API
return pub;
}());
var doc = document;
var el = doc.getElementById('output');
window.setInterval(function(){
/// call your function here
el.innerHTML = clock.what.time(clock.now);
}, 500);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rack.pub/clock.min.js"></script>
<h2 id='output'></h2>

I am having trouble with resetting the counter in jquery (clickfunction)

I am trying to repeat the clickfunction but it will only repeat twice. After that the counter disappears. I don't know what the cause of this is. H
var divClone = $("#target").clone();
var divClone = $("#output").clone();
var clickCount = 0;
$('#target').click(function() {
if ( clickCount < 6){
clickCount++;
$('#output').html(function(i, val) { return val*1+1 });
} else {
clickCount = 0;
$("#output").replaceWith(divClone);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="target" type="button">Click Me</button>
<div id="output">0</div>
Note that I am quite new to programming.
Thanks in advance.
Edit: Sorry, I don't want it to be automatic. After every 6 clicks the counter should reset to zero.
Try this
http://jsfiddle.net/zRX2D/2707/
var clickCount = 0;
$('#target').click(function() {
if ( clickCount < 6){
clickCount++;
} else {
clickCount = 0;
}
$('#output').html(clickCount);
});
Try this:
var clickCount = 0;
$('#target').click(function() {
if (clickCount++ < 6) {
$('#output').html(function(i, val) {
return val * 1 + 1
});
} else {
clickCount = 0;
$('#output').html('0');
}
});
Demo: https://jsfiddle.net/tusharj/zRX2D/2708/
OR
Simple:
var clickCount = 0;
$('#target').click(function () {
$('#output').html(++clickCount % 7);
});
Demo: https://jsfiddle.net/tusharj/zRX2D/2711/
Check following:
var clickCount = 0;
$('#target').click(function() {
clickCount = clickCount < 6 ? clickCount+=1 : 0;
$("#output").text(clickCount);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="target" type="button">Click Me</button>
<div id="output">0</div>

how to stop a message from a javascript timer from repeating?

I have a timer for my game, but the message will keep going on the mage, so it says it multiple times, i was wondering how you can get it to say it once.
<head>
<script type="text/javascript">
var c=10;
var t;
var timer_is_on=0;
function timedCount() {
document.getElementById('txt').value = c;
c = c - 1;
if (c == -1||c < -1){
var _message = document.createTextNode("You have mined 1 iron ore!");
document.getElementById('message').appendChild(_message);
startover();
}
}
function startover() {
c = 10;
clearTimeout(t);
timer_is_on=0;
doMining();
}
function doMining() {
if (!timer_is_on) {
timer_is_on = true;
t = setInterval(function () {
timedCount();
}, 1000);
}
}
</script>
<SPAN STYLE="float:left">
<form>
<input type="button" value="Mining" onClick="doMining()">
<input type="text" id="txt">
</form>
</SPAN>
<html>
<center>
<div id='message'></div>
Instead of setInterval use window.setTimeout.
This will trigger the function only once.
Edit: if you mean you want one message to appear and update every time, first add global counter:
var mineCount = 0;
Then change the code to this:
if (c <= -1) {
mineCount++;
var _message = "You have mined " + mineCount + " iron ore" + ((mineCount > 1) ? "s" : "") + "!";
document.getElementById('message').innerHTML = _message;
startover();
}
This will assign the contents of the element instead of adding to it each time.
Your startOver function calls doMining(). Surely, it shouldn't...?

Categories

Resources