how to calculate the time keydown to keyup - javascript

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>

Related

how to make to stop on specific number when button clicked

<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>

Changing interval time with a click of a button Javascript

I am trying to modify this code so it changes the interval time with a click of a button but I'm failing miserably. Pretty sure that the solution is very simple. Appreciate any help. Thanks!
// define quotes array
var quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
var quoteIndex = 0;
// get interval time
var interval = document.getElementById("interval").value;
// set target element
var $target = $('.container').find('h1');
// create timer function
var quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
// fire it up..!
$(document).ready(function() {
setInterval(quoteTimer, interval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="interval" id="interval" value="" placeholder="Time" />
<input type="submit" name="button" id="button" value="Run" />
<div class="container">
<h1></h1>
</div>
We are adding this piece of code to yours :
// Handle the button click to stop the current setInterval and to launch a new one
$('#button').click(() => {
clearInterval(intervalDescriptor);
intervalDescriptor = setInterval(quoteTimer, parseInt($('#interval').val(), 10));
});
// define quotes array
const quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
let quoteIndex = 0;
// get interval time
const interval = document.getElementById("interval").value;
// set target element
const $target = $('.container').find('h1');
// create timer function
quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
let intervalDescriptor = false;
// Handle the button click to stop the current setInterval and to launch a new one
$('#button').click(() => {
clearInterval(intervalDescriptor);
intervalDescriptor = setInterval(quoteTimer, parseInt($('#interval').val(), 10));
});
// fire it up..!
$(document).ready(function() {
intervalDescriptor = setInterval(quoteTimer, interval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="interval" value="" placeholder="Time" />
<input type="button" id="button" value="Run" />
<div class="container">
<h1></h1>
</div>
updated your jsfiddle
Just stop older timer and start new timer with new interval
Changes
$("#button").on("click", function() {
let v = parseInt($("#interval").val());
clearTimeout(intervalval);
intervalval = setInterval(quoteTimer, v);
})
You can clear it using clearInterval and set it again with the interval.
var intervalId;
$(function(){
intervalId = setInterval(quoteTimer, interval);
});
$("button").click(function(){
if (intervalId) clearInterval(intervalId);
intervalId = setInterval(quoteTimer, interval);
});
var quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
var quoteIndex = 0;
// get interval time
var interval = document.getElementById("interval").value;
$('#button').click(function(){
var intervl=$('#interval').val();
intervl=intervl+"000";
setInterval(quoteTimer, intervl);
})
// set target element
var $target = $('.container').find('h1');
// create timer function
var quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
// fire it up..!
$(document).ready(function() {
//setInterval(quoteTimer, interval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="interval" id="interval" value="" placeholder="Time in seconds" />
<input type="submit" name="button" id="button" value="Run" />
<div class="container">
<h1></h1>
</div>
Add a button click event and set the value to the setInterval function.
var quotes = [
"AAAA",
"BBBB",
"CCCC"
];
$('#button').click(function(){
var quoteIndex = 0;
var interval = document.getElementById("interval").value;
console.log(interval);
var $target = $('.container').find('h1');
setInterval(function(){
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}, interval*1000);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="text" name="interval" id="interval" value="" placeholder="Time" />
<input type="submit" name="button" id="button" value="Run" />
<div class="container">
<h1></h1>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</div>
</body>
</html>
#Esko means to attach click event to button so on click of button event will fire with text value.
check below code.
var intervalID;
// fire it up..!
$(document).ready(function() {
$('#button').click(function(){
var interval = document.getElementById("interval").value;
clearTimeout(intervalID);
intervalID = setInterval(quoteTimer, interval);
});
});
It should be this instead:
// fire it up..!
$("#button").click(function() {
// define quotes array
var quotes = [
"AAAA",
"BBBB",
"CCCC"
];
// initialise current quote index
var quoteIndex = 0;
// get interval time
var interval = document.getElementById("interval").value;
// set target element
var $target = $('.container').find('h1');
// create timer function
var quoteTimer = function() {
// set target text to current quote
$target.fadeIn().text(quotes[quoteIndex]);
// increment the current index, or reset to 0 if on the last quote
quoteIndex = quoteIndex < quotes.length - 1 ? quoteIndex + 1 : 0;
}
setInterval(quoteTimer, interval);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="text" name="interval" id="interval" value="" placeholder="Time" />
<input type="submit" name="button" id="button" value="Run" />
<div class="container">
<h1></h1>
</div>
Remember that you also want to cancel the previous timer and start another one on click. I didnĀ“t add that part to the code.

how to change the value of input box just for display in html 5 web page

I have a textfield in which i am entering data i want that if user enter 1000 then it show 1,000 in textfield but this same value 1000 is also used in calculations further so how to solve this if user enter 1000 then just for display it show 1,000 and if we use in calcualtion then same var shows 1000 for calculating.
<HTML>
<body>
<input type="text" id="test" value="" />
</body>
<script>
var c=document.getElementById(test);
</script>
</html>
so if c user enter 1000 then it should dispaly 1,000 for dispaly one and if user uses in script
var test=c
then test should show 1000
document.getElementById returns either null or a reference to the unique element, in this case a input element. Input elements have an attribute value which contains their current value (as a string).
So you can use
var test = parseInt(c.value, 10);
to get the current value. This means that if you didn't use any predefined value test will be NaN.
However, this will be evaluated only once. In order to change the value you'll need to add an event listener, which handles changes to the input:
// or c.onkeyup
c.onchange = function(e){
/* ... */
}
Continuing form where Zeta left:
var testValue = parseInt(c.value);
Now let's compose the display as you want it: 1,000
var textDecimal = c.value.substr(c.value.length-3); // last 3 characters returned
var textInteger = c.value.substr(0,c.value.length-3); // characters you want to appear to the right of the coma
var textFinalDisplay = textInteger + ',' + textDecimal
alert(textFinalDisplay);
Now you have the display saved in textFinalDisplay as a string, and the actual value saved as an integer in c.value
<input type="text" id="test" value=""></input>
<button type="button" id="get">Get value</input>
var test = document.getElementById("test"),
button = document.getElementById("get");
function doCommas(evt) {
var n = evt.target.value.replace(/,/g, "");
d = n.indexOf('.'),
e = '',
r = /(\d+)(\d{3})/;
if (d !== -1) {
e = '.' + n.substring(d + 1, n.length);
n = n.substring(0, d);
}
while (r.test(n)) {
n = n.replace(r, '$1' + ',' + '$2');
}
evt.target.value = n + e;
}
function getValue() {
alert("value: " + test.value.replace(/,/g, ""));
}
test.addEventListener("keyup", doCommas, false);
button.addEventListener("click", getValue, false);
on jsfiddle
you can get the actual value from variable x
<html>
<head>
<script type="text/javascript">
function abc(){
var x = document.getElementById('txt').value;
var y = x/1000;
var z = y+","+ x.toString().substring(1);
document.getElementById('txt').value = z;
}
</script>
</head>
<body>
<input type="text" id="txt" value="" onchange = "abc()"/>
</body>
This works with integer numbers on Firefox (Linux). You can access the "non-commaed"-value using the function "intNumValue()":
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
String.prototype.displayIntNum = function()
{
var digits = String(Number(this.intNumValue())).split(""); // strip leading zeros
var displayNum = new Array();
for(var i=0; i<digits.length; i++) {
if(i && !(i%3)) {
displayNum.unshift(",");
}
displayNum.unshift(digits[digits.length-1-i]);
}
return displayNum.join("");
}
String.prototype.intNumValue = function() {
return this.replace(/,/g,"");
}
function inputChanged() {
var e = document.getElementById("numInp");
if(!e.value.intNumValue().replace(/[0-9]/g,"").length) {
e.value = e.value.displayIntNum();
}
return false;
}
function displayValue() {
alert(document.getElementById("numInp").value.intNumValue());
}
</script>
</head>
<body>
<button onclick="displayValue()">Display value</button>
<p>Input integer value:<input id="numInp" type="text" oninput="inputChanged()">
</body>
</html>

Can't figure out Javascript Countdown

I need help making a Countdown timer!
The user types a value into a text field, the timer starts when a button is clicked.
The timer text decreases by one every second until it reaches zero.
I have code for the first step, but can't seem to get the second step to work. I know it needs to include a setTimeout and loop.
Heres the code so far :
HTML-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div id="form">
<h2> COUNTDOWN</h2>
Seconds: <input type="text" name="seconds" id="seconds" /> <input type="button" value="Start!" id="start" /> <input type="button" value="Pause" id="pause" />
</div>
<div id="info">
</div>
<div id="countdown">
</div>
<script src="script.js"></script>
</body>
</html>
JAVASCRIPT-
window.onload = function(){
var startButton = document.getElementById("start");
var form = document.getElementById("seconds");
var pause = document.getElementById("pause");
var secDiv = document.getElementById("countdown");
var editSec = document.createElement("h1");
startButton.onclick = function (){
editSec.innerHTML = form.value;
secDiv.appendChild(editSec);
};
};
Here it goes:
var globalTime = form.value; //receive the timer from the form
var secDiv = document.getElementById("countdown");
function decreaseValue() {
globalTime = globalTime - 1;
secDiv.innerHTML = globalTime;
}
startButton.onclick = function (){
setTimeout(decreasValue(),1000);
};
//clear out the timers once completed
You need to use setInterval, not setTimeout. Add this code to the onclick function:
editSec.id = "editSec";
window.cdint = setInterval(function(){
var origVal = parseInt(document.getElementById("editSec").innerHTML);
document.getElementById("editSec").innerHTML = origVal - 1;
if(origVal - 1 <= 0){
window.cdint = clearInterval(window.cdint);
}
}, 1000);
Use setInterval
var time = 100;
var countdown = function(){
secdiv.innerHTML = time;
time--;
}
setInterval(countdown,1000);
You can use setTimeout if you want :
startButton.onclick = function () {
var value = parseInt(form.value);
editSec.innerHTML = value;
secDiv.appendChild(editSec);
setTimeout(function () {
editSec.innerHTML = --value < 10
? '<span style="color:red">' + value + '</span>'
: value;
if (value) {
setTimeout(arguments.callee, 1000);
}
}, 1000);
};

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