Please I want to create a button that can be clicked only once in 24hrs in js but I don't really know how to put it up.
<html>
<head>
<title>Disable Button</title>
<script>
function doSomething () {
document.getElementById("myButton").disabled = true;
document.getElementById("myButton").disabled = false;}
</script>
</head>
<body>
<input type="button" id="myButton" onclick="doSomething()"
value="Click Here To Do Something"/>
</body>
</html>
window.onload = () => {
//on load of the page it will check for same day and disable/enable.
let lastclicked = localStorage.getItem('lastclicked') || '';
document.getElementById("myButton").disabled = lastclicked === new Date().toDateString();
}
function doSomething () {
localStorage.setItem('lastclicked', new Date().toDateString());
document.getElementById("myButton").disabled = true;
}
you need to save to date and time of the last trigger somewhere in local storage or cookies so next when the button is triggered it checked the date in storage if that exists then it will check the date.
hope so it will work for you.
var todayclick = true;
var buttonval = document.getElementById("myButton");
buttonval.click(function() {
if (todayclick ) {
alert("Error!");
}
else {
variable += 1;
todayclick = false;
}
setTimeout(function() {
todayclick = true;
}, 86400);
});
Related
I have a button with an "onclick" function that disables the button for 15 seconds. After that it will be automatically clickable, but in between 15 seconds of time period after a click, if I do refresh the page, it doesn't count the remaining seconds and the button is now clickable.
function up(){
$(document).ready(function () {
$("#upside").attr("disabled", true);
document.getElementById("downside").disabled = true;
setTimeout(function () {
$("#upside").removeAttr("disabled");
$("#downside").removeAttr("disabled");
window.location ='/Balnce_add';
},15000);
});
}
And here is my HTML button code:
<button id="upside" onclick="up()" type="submit" class="btn btn-success">Up</button>
The idea is save the startTime to localStorage. And then when we reload page, we will get the remainingTime = startTime + timer - currentTime. If remainingTime > 0, we will keep disable the button. If not, we do nothing.
And based on that idea, I updated your code to let it works. You can check the demo by the below code:
<html>
<head>
<title>Demo</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="upside" onclick="up(true)" type="submit" class="btn btn-success">Up</button>
<script>
function getRemainingTimer(isNew) {
var now = new Date();
var timer = 15000;
var remainingTimer = 0;
var startTime = localStorage.getItem("startTime");
if (startTime === null) {
if (!isNew) return 0;
localStorage.setItem("startTime", now.getTime());
remainingTimer = timer;
} else {
remainingTimer = timer + parseInt(startTime) - now.getTime();
}
return remainingTimer;
}
function up(isNew) {
var remainingTimer = getRemainingTimer(isNew);
console.log(remainingTimer);
if (remainingTimer > 0) {
$("#upside").attr("disabled", true);
$("#downside").attr("disabled", true);
var timeout = setTimeout(function() {
$("#upside").removeAttr("disabled");
$("#downside").removeAttr("disabled");
window.location = '/Balnce_add';
localStorage.removeItem("startTime");
}, remainingTimer);
} else {
localStorage.removeItem("startTime");
}
}
up(false);
</script>
</body>
</html>
Also, you can check the live demo at https://codepen.io/tuandaodev/pen/NWgBjbv
It depends on how the app is setup, but an easy way to do it would be to store something in localhost with the ID of the button was clicked.
myButton.addEventListener('click', (evt) => {
evt.preventDefault();
let dateTime = new Date();
localStorage.setItem('clickedButtons', [{id: myButton.id, clickedAt: dateTime}]
});
$(document).ready(() => {
let storageButton = localStorage.getItem('clickedButtons')[0];
let dateTime = new Date();
if (dateTime - storageButton.clickedAt < 15000) {
let btn = $(`#${storageButton.id}`);
btn.attr('disabled') = true;
}
})
I wrote this pretty quickly so it's probably a bit rough, but the general idea is when the button is clicked, add something to localstorage with the time it was clicked, and on page load check localstorage, and if it hasn't been 15 seconds since the button was clicked, disable it
I wrote the function for check if button was clicked twice and if it was to measure the time between two clicks. It has to prevent multiple clicks in short time.
Button click:
$("#Save").click(function () {
dateTime1 = new Date().getTime();
BtnId = this.id;
showSaveDialog();
});
And measuring function:
ButtonWasTriggeredTwice: function () {
var result = false;
var currentTime = new Date().getTime();
var time = currentTime - dateTime1;
if (PreviousBtn === null) {
result= false;
} else {
if (PreviousBtn === BtnId) {
if ( time < 1500) {
result = true;
}
else result = false;
}
else {
result= false;
}
}
PreviousBtn = BtnId;
BtnId = null;
return result;
}
BtnId and PreviosusBtn are global scope variables.
The strange thing is this function works great when I set breakpoints in debugger. If I switch off debugger function blocks every next click on button, no matter what time interval is between clicks
You can use this solution with unbind and timeout, like this:
HTML
<input type="button" id="Save" value="save me" />
JS:
function saveEventButton(){
$("#Save").click(function () {
alert('saved!');
$("#Save").unbind('click');
setTimeout(function(){
saveEventButton();
}, 5000); // 5sec
});
}
saveEventButton();
This is the JSFiddle
UPDATE This solution is a mix from mine and Revish Patel solution
function disableTimeout(_this){
$(_this).prop('disabled','disabled');
setTimeout(function(){
$(_this).prop('disabled','');
}, 5000); // 5sec
}
$("#Save").click(function () {
alert('saved!');
disableTimeout(this);
});
This is the JSfiddle
You can also disable button when you first click is performed.
$(document).ready(function () {
$("#Save").click(function(){
$('#Save').prop('disabled','disabled');
// Perform your button click operation
});
});
I was working on a Timer code and its working fine but I'm unable to trigger on button click. I believe there is a silly mistake that I'm not able to figure out and was looking for help.
When I click on button, I get following error in console.
Uncaught ReferenceError: startTimer is not defined
I even have tried using $(document).ready() and defined functions in it still no luck.
Code
function timer(){
var time = {
sec:00,
min:00,
hr:00
}
var max = 59;
var interval = null;
function update(str){
time[str]++;
time[str] = time[str]%60;
if(time[str] == 0){
str == "sec"? update("min"):update("hr");
}
print(str);
}
function print(str){
var _time = time[str].toString().length == 1?"0" + time[str]:time[str];
document.getElementById("lbl"+str).innerText = _time;
}
function initInterval(){
interval = setInterval(function(){
update("sec");
},1000);
}
function stopTimer(){
clearInterval(interval);
}
return {
'init': initInterval,
'stop': stopTimer
}
};
var time = new timer();
function startTimer(){
time.init();
}
function endTimer(){
time.stop();
}
<div>
<span id="lblhr">00</span>
: <span id="lblmin">00</span>
: <span id="lblsec">00</span>
</div>
<button onclick="startTimer()">Start</button>
<button onclick="endTimer()">Stop</button>
I'm looking for pure JS solution, and not JQuery($(btnId).on("click")).
Link to JSFiddle
As I mentioned in a comment, using innerText won't work in most browsers, use innerHTML. This should work:
function timer(){
var time = {
sec:00,
min:00,
hr:00
}
var max = 59;
var interval = null;
function update(str){
time[str]++;
time[str] = time[str]%60;
if(time[str] == 0){
str == "sec"? update("min"):update("hr");
}
print(str);
}
function print(str){
var _time = time[str].toString().length == 1?"0" + time[str]:time[str];
document.getElementById("lbl"+str).innerHTML = _time;
}
function initInterval(){
interval = setInterval(function(){
update("sec");
},1000);
}
function stopTimer(){
clearInterval(interval);
}
return {
'init': initInterval,
'stop': stopTimer
}
};
var time = new timer();
function startTimer(){
time.init();
}
function endTimer(){
time.stop();
}
<div>
<span id="lblhr">00</span>
: <span id="lblmin">00</span>
: <span id="lblsec">00</span>
</div>
<button onclick="startTimer()">Start</button>
<button onclick="endTimer()">Stop</button>
So, your jsfiddle doesn't work because jsfiddle isn't expecting you to assign the onclick event in the HTML section.
You need to migrate that to the javascript section. In the HTML you need to assign an id to each button. Then, in the javascript section, have something like
document.getElementById("bStart").onclick = startTimer;
I also noticed that you have startTimer_out() as a function, but your HTML is trying to call startTimer().
Looks like it may just a jsfiddle thing.
I have two JavaScript "onload" functions that I am trying to run on a webpage: a visual timer and a auto refresh function. I have implemented both in my webpage but although the timer runs, the Auto Refresh function will not run unless I remove the visual timer function from the script.
Here is the code for the webpage:
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>test</TITLE>
</head>
<body onload="JavaScript:timedRefresh(15000); timedText();">
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function () {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
</script>
<input type="text" id="txt" />
</body></HTML>
Any help in solving this problem would be greatly appreciated.
try with a small change:call timedRefresh() inside window.onload's timetext() function not in body onload.
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>test</TITLE>
</head>
<body>
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
timedRefresh(15000);
var timer = setInterval(function () {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
</script>
<input type="text" id="txt" />
</body></HTML>
The problem is the second one overrides the first. That is what you should be using addEventListener to add events.
window.addEventListener('load', timedText, false);
window.addEventListener('load', function(){timedRefresh(15000);}, false);
and if you need to support older IEs you need to look at attachEvent
BUT looking at the code why are you running two setTimeouts when all you need to do is when it hits zero call the redirect.
You can add multiple onload events using the addEventListener method, like so:
window.addEventListener("load", timedText, false);
window.addEventListener("load", timedRefresh(15000), false);
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function() {
if (counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",
timeoutPeriod);
}
You can find out more information about addEventListener here.
Here's a working codepen.
I noticed my users sometimes click the buttons twice, maybe no one told them one click is enough.
What's the best way to prevent the double-click?
I basically hide the button and show a "loading" gif, but that apparently is not enough...
Usually disabling/hiding/replacing the button should work. If they are real fast, try setting a variable to false when your script starts, return if it's true, set it to true after the first click.
var alReadyClicked = false;
function click(){
if (alreadyClicked)
return false;
alreadyClicked = true;
}
Don't forget to set it to false when the user can click again.
If they are clicking fast enough to fire the double click event, return false.
ondblclick="return false"
EDIT: This will not cancel the single click event so problem would still exist.
I just found out the jQuery funcion .one(), that may be useful great for this kind of purpose! great!
The equivalence to JQuery .one() may be the once option on AddEventListner like:
function doSubmit () { /* your code */ }
btn = document.getElementById ('foo');
btn.addEventListener ('click', doSubmit, {once: true});
Reference: javascript - JS equivalent for jQuery one() - Stack Overflow
Another example using a flag
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>test dbl click</title>
</head>
<body>
<button id="btn1">Click Away</button>
<div id="out"></div>
<script type="text/javascript">
function addMessage( msg ){
document.getElementById("out").innerHTML += (new Date().toTimeString()) + " : " + msg + "<br/><br/>";
}
function singleClick(){
addMessage( "single");
}
function addDoubleClickProtection( element, fncToCall ){
var isClicked = false;
var timer = null;
element.onclick = function(){
if(!isClicked){
isClicked = true;
timer = window.setTimeout( function(){ isClicked = false; }, 200);
return fncToCall();
}
}
}
addDoubleClickProtection( document.getElementById("btn1"), singleClick );
</script>
</body>
</html>
Simple method by counting the submit button click and with minimum decoration will:
<script>
var click_count = 0;
function submit_once () {
document.forms.A.elements.cmd.forEach(
function(e,i,l){e.style.color="#888";});
return (click_count++ > 1);
}
function reset_count () {
document.forms.A.elements.cmd.forEach(
function(e,i,l){e.style.color="unset";});
click_count = 0;
}
</script>
<form name="A">
<button type="submit" name="cmd" value="doAdd"
onclick="return submit_once();">Do add</button>
<button type="submit" name="cmd" value="doDel"
onclick="return submit_once();">Do delete</button>
</form>
You can create a util function once which will take CB function. And all logic handles seamlessly. You don't have to create a global variable to count or update.
function once(cb) {
let once = false;
return (...args) => {
!once && cb(...args);
once = true;
};
}
// How to use it.
// Create/bind function
const log = once((data) => {
console.log(data);
});
// Use it
Promise.resolve("hellowold").then(log).then(log);
Above line print only once.