I want my button to hide after a certain time; I've tried every idea I had, but I still can't get over the problem.
function myTimer() {
var now = Date().now;
var startTime = new Date();
var endTime = new Date();
startTime.setHours(11, 55, 0);
endTime.setHours(21, 51, 0);
var button = document.getElementById("verse1");
if ((now < startTime || now > endTime) && button.style.visibility != "hidden")
button.style.visibility = "hidden";
else if (button.style.visibility != "visible")
button.style.visibility = "visible";
}
window.setInterval(myTimer, 500);
<button id="verse1">hello</button>
Use Date.now(); Date().now is undefined.
var now = Date.now();
Related
How to make multiple countdown timers at the same page using the codes below?
I tried to make another countdown timer by making another var start = document.getElementById("start2"); and var dis = document.getElementById("display2"); but when I click the 1 button only the second countdown timer is working,
var start1 = document.getElementById("start1");
var dis1 = document.getElementById("display1");
var finishTime1;
var timerLength1 = 10;
var timeoutID1;
dis1.innerHTML = "" + timerLength1;
if(localStorage.getItem('myTime')){
Update();
}
start1.onclick = function () {
localStorage.setItem('myTime', ((new Date()).getTime() + timerLength1 * 1000));
if (timeoutID1 != undefined) window.clearTimeout(timeoutID1);
Update();
}
function Update() {
finishTime1 = localStorage.getItem('myTime');
var timeLeft = (finishTime1 - new Date());
dis1.innerHTML = "" + Math.max(timeLeft/1000,0)
timeoutID1 = window.setTimeout(Update, 100);
}
var start2 = document.getElementById("start2");
var dis2 = document.getElementById("display2");
var finishTime2;
var timerLength = 100;
var timeoutID;
dis2.innerHTML = "" + timerLength;
if(localStorage.getItem('myTime')){
Update();
}
start2.onclick = function () {
localStorage.setItem('myTime', ((new Date()).getTime() + timerLength * 1000));
if (timeoutID != undefined) window.clearTimeout(timeoutID);
Update();
}
function Update() {
finishTime2 = localStorage.getItem('myTime');
var timeLeft = (finishTime2 - new Date());
dis2.innerHTML = "" + Math.max(timeLeft/1000,0)
timeoutID = window.setTimeout(Update, 100);
}
<span id="display2"></span><button id="start1">START1</button>
<br><br>
<span id="display2"></span><button id="start1">START1</button>
enter code here
You are using the same id for localStorage. Actually it is better to create isolated context through function or class, then it will be easier to handle as much counters as you wish. Also you can use setInterval instead of setTimer
One more tip: when you assign number to string field no need to write "" + value, because number authomatically will be converted into string
const createCounter = (startElementId, displayElementId, localStorageId, timerLength) => {
const startElement = document.getElementById(startElementId),
displayElement = document.getElementById(displayElementId)
let timeoutID
displayElement.innerHTML = timerLength
const storageValue = localStorage.getItem(localStorageId)
if (storageValue) startTimer()
startElement.onclick = () => {
const value = (new Date()).getTime() + timerLength * 1000
localStorage.setItem(localStorageId, value)
startTimer()
}
function startTimer () {
if (timeoutID) clearInterval(timeoutID)
timeoutId = setInterval(updateTime, 100)
}
function updateTime (finishTime) {
finishTime = finishTime || localStorage.getItem(localStorageId)
const timeLeft = finishTime - new Date()
displayElement.innerHTML = Math.max(timeLeft / 1000, 0)
}
}
// run first timer for elements with ids start1 and display1
createCounter('start1', 'display1', 'someId1', 10)
// run second timer for elements with ids start1 and display1
createCounter('start2', 'display2', 'someId2', 60)
html
<button id=start1>Start</button>
<div id=display1></div>
<button id=start2>Start</button>
<div id=display2></div>
I have been trying to make a timer disappear when it reaches 00:00 but everytime I try something it just hides the div right away.
Here is the code I am using:
$(document).ready(function(e) {
var $worked = $("#worked");
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1] + ":" + ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worked">00:10</div>
I have created an example for you. For this example I have changed the timer's interval to 10ms so you can see the result quicker. Also instead of setting a setTimeout to run update inside the function update. You can use setInterval. I have also added a check inside the update function that checks if the time is 00:00. If it is true, then it invalidates the interval by calling clearInterval(timer); and runs $worked.hide()
$(document).ready(function (e) {
var $worked = $("#worked");
var timer = setInterval(update, 10);
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1]+":"+ts[2]);
$worked.html(ts[1]+":"+ts[2]);
if(ts[1] === '00' && ts[2] === '00') {
clearInterval(timer);
$worked.hide();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="worked">01:00</div>
Here's another approach :)
$(document).ready(function(e) {
var $worked = $("#timer");
var startTime = new Date().getTime();
var now, currentDistance;
setInterval(function update() {
now = new Date().getTime();
currentDistance = 10000 - now + startTime;
if (currentDistance > 0) {
$worked.html(parseInt(currentDistance / 1000) + " seconds, " + (currentDistance % 1000) + " ms left!");
} else {
$worked.hide();
}
}, 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="timer" style="background-color: rgb(190, 190, 220); width: 200px; text-align: center"></div>
At the moment I have two buttons, "Green" and "Red". Once "Green" is clicked the text in the div (red as default) goes green. And when the "Red" button is clicked the text goes red. These are two separately working buttons that carry out the function I want.
But I want there to be just one button. The Default button will be called "Green", once clicked it will change the font of the div to green and the button will change name to "Red". Once "Red" is clicked it will turn the font back to red and the button back to "Green".
How do I go about this using javascript? JQuery won't be much help to me as I am trying to master javascript at the moment.
Here is my current html with my two working buttons:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="clock3.css">
<link href='http://fonts.googleapis.com/css?family=Inconsolata' rel='stylesheet' type='text/css'>
<title> Clock Part III </title>
<script type="text/javascript">
window.onload = time;
function time () {
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
if (hours < 10)
hours = "0" + hours
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
times = hours+':'+minutes+':'+seconds;
document.getElementById('timer').innerHTML = times;
setTimeout(time, 1000);
}
var random = Math.floor(Math.random() * 2);
</script>
</head>
<body>
<button type="button" id="green" onclick = 'document.getElementById("timer").style.color = ("#088A08");'>Green</button>
<button type="button" id="red" onclick = 'document.getElementById("timer").style.color = ("#FF0000");'>Red</button>
<h1> Clock </h1>
<div id="timer"></div>
</body>
</html>
Thanks in advance!:)
just set a flag like
var isGreen = true;
and create a function
function colorControl (el){
if(isGreen){
document.getElementById("timer").style.color = ("#088A08");
isGreen= false;
el.innerHTML = "RED";
return;
}
document.getElementById("timer").style.color = ("#FF0000");
isGreen = true;
el.innerHTML = "Green";
}
And your button like that:
<button type="button" id="green" onclick ="colorControl(this)">Green</button>
Green
function changeColor(self)
{
if(self.innerHTML == "Green")
{
document.getElementById("timer").style.color = "#088A08";
self.innerHTML = "Red";
}
else if(self.innerHTML == "Red")
{
document.getElementById("timer").style.color = "#FF0000";
self.innerHTML = "Green";
}
}
You can add the click event listener using JavaScript instead of HTML.
Within the listener, check the button's textContent property. With it, you can set the timer color and change the button's text:
var button = document.getElementById('button');
button.addEventListener('click',function() {
var timer = document.getElementById('timer');
if(this.textContent === 'Red') {
timer.style.color= '#ff0000';
this.textContent= 'Green';
}
else {
timer.style.color= '#088a08';
this.textContent= 'Red';
}
});
function time () {
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
if (hours < 10) hours = "0" + hours
if (minutes < 10) minutes = "0" + minutes
if (seconds < 10) seconds = "0" + seconds
times = hours+':'+minutes+':'+seconds;
document.getElementById('timer').innerHTML = times;
setTimeout(time, 1000);
}
var button = document.getElementById('button');
button.addEventListener('click',function() {
var timer = document.getElementById('timer');
if(this.textContent === 'Red') {
timer.style.color= '#ff0000';
this.textContent= 'Green';
}
else {
timer.style.color= '#088a08';
this.textContent= 'Red';
}
});
time();
#timer {
color: red;
}
<div id="timer"></div>
<button id="button">Green</button>
Create a toggle() function...
function toggle () {
var color;
if (document.getElementById('button').style.color == "green") {
color = "red";
} else {
color = "green";
}
document.getElementById('button').style.color = color;
document.getElementById("timer").style.color = color;
}
Set the button and timer default color with...
...style="color:green;"...
I need to create a popup window that open on page load AND only between 11am and 7pm EST.
I have the auto pop up working, but am having trouble adding the time variance.
Please advise.
EDITED
<!--chat-->
<script type="text/javascript">
$(document).ready(function() {
var currentTime = new Date((new Date()).toUTCString());
var startTime = new Date((new Date()).toUTCString());
var endTime = new Date((new Date()).toUTCString());
startTime.setUTCHours(8);
endTime.setUTCHours(19);
//set times to EST. (UTC -5)
currentTime.setHours(currentTime.getHours() - 5);
startTime.setHours(startTime.getHours() - 5);
endTime.setHours(endTime.getHours() - 5);
//code to determine your variables goes here
var mylink = "https://mylink.com";
var windowname = "Chat Client";
if (currentTime < endTime && currentTime > startTime) {
popup(mylink, windowname);
}
});
function popup(mylink, windowname)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
window.open(href, windowname, 'width=470,height=700,scrollbars=yes');
return false;
}
</SCRIPT>
//bad code removed to save space
EDIT:
To work in any timezone:
//bad code removed to save space
UPDATED:
Added jquery tags and function definition to demonstrate code structuring as per request.
UPDATE2:
$(document).ready(function() {
var currentTime = toUTC(new Date());
var startTime = toUTC(new Date());
var endTime = toUTC(new Date());
startTime.setHours(11);
startTime.setMinutes(0);
startTime.setSeconds(0);
endTime.setHours(19);
endTime.setMinutes(0);
endTime.setSeconds(0);
//set times to EST. (UTC -4)
currentTime.setHours(currentTime.getHours() - 4);
//code to determine your variables goes here
//var mylink =
//var windowname =
if (currentTime < endTime && currentTime > startTime) {
popup();
}
});
function popup() {
//put function code here
$('body').append("Here is some text");
}
function toUTC(inDate) {
inDate.setMinutes(inDate.getMinutes() + inDate.getTimezoneOffset());
return inDate;
}
And here it is in a fiddle.
But it's only work with local time.
var date = new Date();
var hours = date.getHours();
if(hours > 11 && hours < 19)
{
// show pop-up
}
I'm having a problem with this JavaScript script. I've tried a number of things to get it to work. The alerts in there at current are there for debugging purposes, and seem to be failing to occur.
Help please?
function checkTime(this_time){
var the_string = "checkTime("+this_time+")";
var now = ((new Date()).getTime());
if(parseInt(now) >= parseInt(this_time)){
document.write("TIMEUP!");
}
alert(now);
alert(this_time);
var t = setTimeout(the_string,300);
}
var the_time = (((new Date()).getTime())+19000);
var the_string = "checkTime("+the_time+")";
var t = setTimeout(the_string,300);
Thanks,
Will.
Seems like you're looking for a countdown?
See this fiddle. The code is simplified to:
var bench = 19000 + new Date().getTime(),
timer = setInterval(
function(){
checkTime(bench);
}
, 1000
);
function checkTime(this_time){
var check = new Date - this_time;
if(check>=0){
alert('time\'s up!');
clearInterval(timer);
}
}
You should use setTimeout with closures instead of strings.
var now = new Date().getTime();
setTimeout(function(){
//your Javascript code here
//"now" can be used here as a closure
}, 300);
Here is a safer and self-contained version. A document.write after load will clear the page completely
http://jsfiddle.net/mplungjan/Zt5k7/
window.onload=function() {
var timer = function (endTime) {
var end = new Date(endTime);
var tId;
this.checkTime=function(){
var now = new Date();
document.getElementById("msg").innerHTML=now.toLocaleString();
if (now.getTime()>=end.getTime()) {
document.getElementById("msg").innerHTML="TIME's UP!";
clearInterval(tId);
}
}
tId = setInterval(this.checkTime,300);
}(new Date().getTime()+5000);
}
or for a proper countdown http://jsfiddle.net/mplungjan/Zt5k7/1/
window.onload=function() {
var timer = function (endTime) {
var end = new Date(endTime);
var tId;
this.checkTime=function(){
var now = new Date();
document.getElementById("msg").innerHTML=now.toLocaleString();
var diff = end.getTime()-now.getTime()
if (diff >= 1) document.getElementById("msg").innerHTML=parseInt(diff/1000)+1;
else {
document.getElementById("msg").innerHTML="TIME's UP!";
clearInterval(tId);
}
}
tId = setInterval(this.checkTime,300);
}(new Date().getTime()+9000);
}
I suppose the code could be made more simple to work.
function checkTime(this_time){
var now = ((new Date()).getTime());
if((now - this_time) >= 0){
document.write("TIMEUP!");
window.clearInterval(timer);
}
}
var t_t = (((new Date()).getTime())+19000);
var timer = window.setInterval(function(){
checkTime(t_t); }
, 300);
Cheers!