<label id="statusLabel">Online</label>
<input type="text" id="txtInput">
<script>
if($('txtInput').keyup()) {
$('#statusLabel').text('typing...');
}
else {
$('#statusLabel').text('online');
}
</script>
I want set statusLabel.text to 'typing' when I'm typing on the keyboard.And statusLabel.text to 'online' when I'm not typing on the keyboard.I have tried this code and It's not working.Is it possible to do so?.Really appreciate if your'll can help.Thanks
This can be done using a timer that gets reset every time a user presses a key in the input field.
The time is used to show the text online after waiting for a certain amount of time when user haven't typed anything, 1 sec in this example.
So after X amount of millisecond the status is set back to online since system waited for X millisecond before shiting label from typing... to online.
var timer = null;
$('#txtInput').keydown(() => {
$('#statusLabel').text('Typing...');
clearTimeout(timer);
timer = setTimeout(() => $('#statusLabel').text('Online'), 1000)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="statusLabel">Online</label>
<input type="text" id="txtInput">
this might help you when user start typing then it will show 'typing...' by default after certain time it will show 'online' :
$('txtInput').keyup(function(){
$('#statusLabel').text('typing...');
function timer(){
$('#statusLabel').text('online');
}
//setTimeout(myFunc,5000);
setTimeout(timer,3000);
});
I would do something like this:
var typing;
var interval = 500;
//on keyup, start the countdown
$('#txtInput').keyup(function() {
$('#statusLabel').text('typing...');
clearTimeout(typing);
if ($('#txtInput').val()) {
typing = setTimeout(doneTyping, interval);
}
});
function doneTyping() {
$('#statusLabel').text('online')
}
Here I use setTimeout and clearTimeout so the text dont flash between typing... and online.
Basic, what it does is that when you start typing, it changes the text, and clears the timer. If you press another key within 0,5 seconds then it will clear the timer once more.
Once you haven't typed anything for 0,5 sec then it will change the text of statusLabel
Demo
var typing;
var interval = 500;
//on keyup, start the countdown
$('#txtInput').keyup(function() {
$('#statusLabel').text('typing...');
clearTimeout(typing);
if ($('#txtInput').val()) {
typing = setTimeout(doneTyping, interval);
}
});
function doneTyping() {
$('#statusLabel').text('online')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="statusLabel">Online</label>
<input type="text" id="txtInput">
var timerID;
$('#txt').keyup(function(){
$('#status').text('Typing...');
timerID = setTimeout(clearThis, 1300);
});
function clearThis(){
$('#status').text('online');
clearInterval(timerID);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="status">Online</label>
<br>
<input type="text" id="txt">
Related
How i can submit form after user complete typing input?
Example: The user started typing. After the introduction of several characters stopped. The form was submited.
Here is a example for you.
var timer;
var doneTypingInterval = 3000; // wait 3 seconds
var $input = $('input');
$input.on('keyup', function () {
clearTimeout(timer);
timer = setTimeout(doneTyping, doneTypingInterval);
});
$input.on('keydown', function () {
clearTimeout(timer);
});
function doneTyping () {
alert('done')
}
Html
<input type="text">
But i don't recommend this. It can be annoying for your user's.
i hope this sample helps :
HTML
<form>
<input name="query" id="query">
<p id="message" > </p>
</form>
JS
function submitForm(){
//do some stuff
}
jQuery(document).ready(function(){
window.timeout=null;
jQuery('#query').on('keyup', function(event){
clearTimeout(window.timeout);
window.timeout = setTimeout(submitForm, 1000); // waits 1 second for user to press a new key
});
});
I am using this function to auto-click a button after 15 seconds. The problem is the user doesn't leave the page after the option is run and it may be re-run again on the same page but the timer continues. In fact, the timer continues even if I do the action myself.
<script type="text/javascript">
time = 15;
interval = setInterval(function() {
time--;
document.getElementById('Label1').innerHTML = "You must choose in " + time + " seconds"
if (time == 0) {
// stop timer
clearInterval(interval);
// click
document.getElementById('thebutton').click();
}
}, 1000)
</script>
So this script should run the timer and "press" the "thebutton" in fifteen seconds and then the timer should stop counting and reset until run again. If the button is pressed manually before 15 seconds it should still reset.
<input type='submit' id='thebutton' value='Done'></input>
Hopefully this is clear. I am still new and learning.
Set a base time and then reset it to that.
<script type="text/javascript">
time = 15;
baseTime = 15;
interval = setInterval(function() {
time--;
document.getElementById('Label1').innerHTML = "You must choose in " + time + " seconds"
if (time == 0) {
// stop timer
clearInterval(interval);
// click
document.getElementById('thebutton').click();
time = baseTime;
return false;
}
}, 1000)
</script>
I had a look at the code and the most critical thing that I think you should look at is that the button has no "onclick" function.
This means that clicking the button does nothing because you have not put a function there that does something when you click it.
I wrote some code that I hope helps:
let time = 15;
const label = document.getElementById("Label1");
const button = document.getElementById("thebutton");
const getText = () => `You must choose in ${time} seconds`;
const interval = setInterval(() => {
time--;
label.innerHTML = getText();
if (time === 0) {
// stop timer
clearInterval(interval);
// click
button.click();
}
}, 1000);
const stopTime = () => {
clearInterval(interval);
time = 15;
label.innerHTML = getText();
};
And in your html something like this:
<input type='submit' id='thebutton' value='Done' onclick="stopTime()" />
Finally I made a small video where I walk through the code, it could be useful as well: https://youtu.be/ZYS9AcxO3d4
Have a great day!
If you only want the button to be clicked once after 15 seconds then you should use the setTimeout() function instead of setInterval().
Then if you do not want the auto-click to happen if the user clicks the button then you would need to add an onClick handler to your button that calls clearTimeout().
I assume you want the label updated as the seconds count down? And it's unclear how the timer is started. Check the below code and see if it does what you expect.
var time, interval;
function stopTimer() {
if (interval) {
clearInterval(interval);
interval = null;
}
time = 15;
}
function timerAction() {
$('#lblStatus').text("You must choose in " + time + " seconds");
if (time-- <= 0) {
stopTimer();
console.log("done!");
$("#btnStop").click();
}
}
function startTimer() {
stopTimer();
timerAction();
interval = setInterval(timerAction, 1000);
}
$("#btnStart").click(function() {
startTimer();
});
$("#btnStop").click(function() {
stopTimer();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id=lblStatus></span>
<button id='btnStart'>Reset / Start</button>
<button id='btnStop'>Stop</button>
If you want to run only once, you can use setTimeout function
setTimeout(your code, 15000);
I currently have a timer , that counts down from 2 minutes.
what I would like to happen is when the button is clicked, it is hidden until the timer runs out and when the timer runs out it is visible/clickable again. I would also like the timer to be hidden until the button is clicked, to be visible when the button is clicked and then to be hidden once the timer runs out.
here is my code
js
function startTimer() {
userInput = 120;
if(userInput.length == 0){
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
function display( notifier, str ) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond( x ) {
return Math.floor(x/60) + ":" + x%60;
}
function setTimer( remain, actions ) {
(function countdown() {
display("countdown", toMinuteAndSecond(remain));
actions[remain] && actions[remain]();
(remain -= 1) >= 0 && setTimeout(countdown, 1000);
})();
}
setTimer(userInput, {
0: function () { alert( "Time Is Up. Please Sumbit Vote."); }
});
}
}
html
<div id="countdown"></div>
<input type="button" onclick="startTimer()" value="Start Timer">
fiddle
http://jsfiddle.net/grahamwalsh/qur9r3d8/
You can hide and unhide the button using JS
JSFiddle
Add an ID to your button
<input id="btn" type="button" onclick="startTimer()" value="Start Timer"/>
JScode
function startTimer() {
//hide button
document.getElementById("btn").style.display = "none";
//un-hide timer
document.getElementById("countdown").style.display = "inline";
userInput = 10;
if (userInput.length == 0) {
alert("Please enter a value");
} else {
var numericExpression = /^[0-9]+$/;
function display(notifier, str) {
document.getElementById(notifier).innerHTML = str;
}
function toMinuteAndSecond(x) {
return Math.floor(x / 60) + ":" + x % 60;
}
function setTimer(remain, actions) {
(function countdown() {
display("countdown", toMinuteAndSecond(remain));
actions[remain] && actions[remain]();
(remain -= 1) >= 0 && setTimeout(countdown, 1000);
})();
}
setTimer(userInput, {
0: function () {
alert("Time Is Up. Please Sumbit Vote.");
//un-hide button
document.getElementById("btn").style.display = "inline";
//hide timer
document.getElementById("countdown").style.display = "none";
}
});
}
}
Here is a fiddle with the solution:
Use the display property:
document.getElementById("button1").style.display="none";
and to show:
document.getElementById("button1").style.display="block";
fiddle
Make sure to add button1 as an id to your button:
<input id="button1" type="button" onclick="startTimer()"
The fiddle shows where you should put this code...
I went ahead and built it from scratch using JQuery as your friend suggested. I think all the answers here using your setTimeout are taking the wrong approach. This is more of a job for setInterval which will provide slightly less performance overhead and much cleaner code.
Working Example: http://codepen.io/Chevex/pen/RNomGG
First, some simple HTML to work with.
<div id="timerDisplay"></div>
<button id="startTimer">Start Timer</button>
Next, a simple timer script.
// Passing a function to $() is the same as $(document).on('ready', function () { ... });
// It waits for the entire page to be loaded before running the function, which is usually what you want.
$(function () {
// Get reference to our HTML elements and store them as variables.
// I prepend them with dollar signs to signify they represent HTML elements.
var $startTimer = $('#startTimer');
var $timerDisplay = $('#timerDisplay');
// The initial time of the timer.
var time = 120;
// Hide the timer display for now, until the button is clicked.
$timerDisplay.hide();
// Set up a click handler on our $startTimer button.
$startTimer.click(function () {
// When the button is clicked, do the following:
// Set the disabled property to true for our button.
// Effectively the same as <button id="startTimer" disabled>Start Timer</button>
$startTimer.prop('disabled', true);
// Fade in our timer display DIV element.
$timerDisplay.fadeIn();
// Set a timeRemaining variable to the value of the initial time.
var timeRemaining = time;
// Declare an interval function that runs every second.
// Also get reference to the intervalId that it returns so we can kill it later.
var intervalId = setInterval(function () {
// Every time the interval runs (every second), do the following:
// Create a formatted countdown timestamp using the timeRemaining.
var timeStamp = Math.floor(timeRemaining/60) + ':' + timeRemaining%60;
// Set the text of our timer display DIV element to our formatted timestamp.
$timerDisplay.text(timeStamp);
// If the timeRemaining is zero, clean up.
if (timeRemaining === 0) {
// Kill the interval function so it doesn't run again.
clearInterval(intervalId);
// Fade out our timer display DIV element.
$timerDisplay.fadeOut();
// Show the alert informing the user the timer is up.
alert('Time is up, please submit a vote :)');
// Re-enable the startTimer button.
$startTimer.prop('disabled', false);
}
// Otherwise subtract one second from the timeRemaining and allow the interval to continue.
else {
timeRemaining--;
}
}, 1000);
});
});
I really need some help with my Javascript countdown timer.
I am trying to make a countdown timer, for a quiz game, that resets and starts over when a button is pressed.
I can get it to reset and start over but if I press the button before time gets to 0, it will count down super fast.
Can anyone help? Here's the code:
<script type="text/javascript">
var countdown;
var time;
function init() {
time = 11;
reset();
trigger();
}
function trigger() {
if(time > 0) {
time--;
document.getElementById('timer').innerHTML = time;
if(time > 0) {
countdown = setTimeout('trigger()', 1000);
}
}
}
function reset() {
clearTimeout(trigger);
}
</script>
<input type="button" value="Reset" onclick="init()" />
<h3 id="timer">10</h3>
Of course I have the basic HTML document set up. The script is inside the tags and there's no difference in timer behavior if I place the script in element.
Thank you in advance!
You're not clearing the timeout in the reset. it should be
clearTimeout(countdown);
like this fiddle
Sorry for that short and meaningless title, but it really is the only one that really describes my problem.
I want (or have to) script a slideshow which (if a checkbox is checked and a time is given) automatically switches the focus on another image.
I already have everything but the automation and am currently working on it.
I thought that comparing the current time with a target time (currentTime + user-input seconds (in Integer)) every 1000 millisecs would be the best way to do it.
However, I don't get why, but it's not working. The calculated target time seems to be correct, since I get a correct difference of the pre-calculated date.getTime() and the calculated one.
I would be very thankful if you could help me.
Here's the JS:
var checkbox_checked;
function timerfn() {
if (checkbox_checked === null || checkbox_checked === false) {
checkbox_checked = true;
var targetTime = new Date();
alert(targetTime.getTime());
var target_sec = targetTime.getSeconds() + dauerSwitch;
targetTime.setSeconds(target_sec);
alert(targetTime.getTime());
// update currentTime every 1 Seconds (1000 Milliseconds)
setInterval(function () {
var current_time = Date.now();
if (targetTime.getTime() == current_time) {
gallery("zur");
}
}, 1000);
} else {
checkbox_checked = false;
}
}
And here's the HTML:
<form>
<input type="checkbox" id="timer" name="timer" onClick="timerfn()">
<input type="text" id="textbox" name="timerParam"
placeholder="Seconds between slides" value=""
onBlur="boxConv()"> //boxConv just converts the String to an Integer. It also checks if it's only numbers
</form>
Thats how i would do it with a little help of jquery ($). I moved the inline code into JS event listener and used the user input as parameter for the interval to make it work.
$(function () {
var intervalTime = 1000,
counter = 1,
interval;
$("#textbox").on("blur", function () {
var inputValue = $(this).val();
try {
//parses the user input into a integer
intervalTime = parseInt(inputValue, 10) * 1000;
} catch (e) {
//could not parse input
}
});
$("#timer").on("click", function () {
if ($(this).is(":checked")) {
interval = setInterval(function () {
//gallery("zur");
//fills the test output
$("#testOutput").val(counter);
counter++;
}, intervalTime); //intervall time is given in milliseconds
} else {
clearInterval(interval);
}
});
});
And here the link to a working example:
http://jsfiddle.net/9Yeuh/2/