Changing the Background image based on time (javascript) - javascript

In the code below I change the background color based on the seconds left in the timer. I am trying to figure out if there is a way to change the background image based on the time.
I have tried to add the following:
var imgArray = ['something.jpg', 'something2.jpg'];
function changeColor(){
if (seconds <= 300 && seconds > 90) {
document.body.style.background = imgArray[0];
}
else if (seconds <= 90 && seconds > 30) {
document.body.style.background = imgArray[1];
}
else (seconds <= 30 && seconds >= 0) {
document.body.style.background = imgArray[0];
}
};
This however does not work. I am unsure what I am doing wrong. Below is my full code:
var seconds = 300; //Variables for the code below
var countdownTimer;
var colorChange; //sets up array of colors
colorChange = ['#7ed473', '#fff194', '#fa8283', 'white']
function secondPassed(){
var minutes = Math.floor(seconds/60); //takes the output of seconds/60 and makes rounds it down. 4.7 = 4, 3.7 = 3. (to keep the minutes displaying right)
var remainingSeconds = seconds % 60; //takes remainder of seconds/60 and displays it. so 270/60 = 4.5 this displays it as 30 so it becomes 4:30 instead of 4.5
if (remainingSeconds < 10) { //if remaining seconds are less than 10 add a zero before the number. Displays numbers like 09 08 07 06
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds; //displays time in the html page 5:06
document.getElementById('countdown2').innerHTML = minutes + ":" + remainingSeconds; //displays the time a second time
if (seconds == 0) {
clearInterval(countdownTimer); //keeps value at zero once it hits zero. 0:00 will not go anymore
alert("Time is Up, Try again");
}
};
function changeColor(){ //this changes the background color based on the time that has elapsed
if (seconds <= 300 && seconds > 90) { //green between 5:00 - 1:30
document.body.style.background = colorChange[0];
}
else if (seconds <= 90 && seconds > 30) { //yellow between 1:30 - 30
document.body.style.background = colorChange[1];
}
else if(seconds <= 30 && seconds >= 0){ // red between 30 - 0
document.body.style.background = colorChange[2];
}
};
function countdown(start){ //code for the button. When button is clicked countdown() calls on secondPassed() to begin count down.
secondPassed();
if (seconds != 0) { //actual code to decrement the time
seconds --;
countdownTimer = setTimeout('countdown()', 1000);
changeColor(); //calls the changeColor() function so that background changes
start.disabled = true; //disables the "start" button after being pressed
}
if (start.disabled = true){ //if one of the 'start' buttons are pressed both are disabled
start2.disabled = true;
}
};
function cdpause() { //pauses countdown
// pauses countdown
clearTimeout(countdownTimer);
};
function cdreset() {
// resets countdown
cdpause(); //calls on the pause function to prevent from automatically starting after reset
secondPassed(); //reverts back to original secondPassed() function
document.getElementById('start').disabled = false; //Enables the "start" button that has been disabled from countdown(start) function.
document.getElementById('start2').disabled = false; //enables the 'start2' button. same as above.
document.body.style.background = colorChange[3]; //Resets background color to white.
};
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<script src = "Timer2.js">
</script>
</head>
<body onload = "cdreset()">
<div id = "timerBackground">
<span id="countdown" class="timer"></span>
<div id = "timerButtons">
<input type="button" value="Start" onclick="countdown(this)" id = "start">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset(seconds = 300)">
</div>
</div>
<div id = "timerBackground2">
<span id="countdown2" class="timer"></span>
<div id = "timerButtons2">
<input type="button" value="Start" onclick="countdown(this)" id = "start2">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset(seconds = 300)">
</div>
</div>
</body>
</html>
My question is how do I get the code to change the background image rather than just changing colors?

You need to set the background with url(..) surrounding the value.
document.body.style.background = "url(" + imgArray[1] + ")";

Related

Why can't I switch between my "stop" and "start" buttons?

I'm making a stopwatch, and my codes is supposed to make the "start" button turn to "stop" button whenever I click on the "start" button and the opposite. My start button seems to work but when I try to switch it to "stop" it doesn't work. I don't know what is wrong, anybody can help me? Thank you so much!
This is my js:
let hours = 0
let seconds = 0
let minutes = 0
//define var to hold 'display' value
let displaySeconds = 0
let displayMinutes = 0
let displayHours = 0
//var to hold "setInterval" function
let interval = null
//Define var to hold stopwatch status
let status = "stopped"
//functions(logic to determine when to increment values,...)
function stopWatch() {
seconds++;
//logic to determine when to flip to next next value
if (seconds / 60 ===1){
seconds = 0;
minutes++;
if(minutes/ 60 ===1){
minutes = 0;
hours++;
}
}
//if second, minute, hrs are only one digits, add a leaing 0 to the value
if(seconds < 10){
displaySeconds = "0" + seconds.toString()
}else{
displaySeconds = seconds
}
if(minutes < 10){
displayMinutes = "0" + minutes.toString()
}else{
displayMinutess = minutes
}
if(hours < 10){
displayHours = "0" + hours.toString()
}else{
displayHours = hours
}
//display updated time values to user
document.getElementById('display').innerHTML = displayHours + ':' + displayMinutes + ":" + displaySeconds
}
function startStop(){
if(status === "stopped"){
//start the stopwatch by calling setInterval function
interval = window.setInterval(stopWatch, 1000)
document.getElementById('startStop').innerHTML = "stop"
status:"started"
}
else{
window.clearInterval(interval)//stop interval from running
document.getElementById('startStop').innerHTML = "start"
status = "stopped"
}
}
This is my html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div id="display">
00:00:00
</div>
<div class="button">
<button id="startStop" onclick="startStop()">Start</button>
<button id="reset">Reset</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
It is because you are using status: "started" instead of status = "started", you are writing the following statement inside the if block
if(status === "stopped"){
interval = window.setInterval(stopWatch, 1000)
document.getElementById('startStop').innerHTML = "stop"
status = "started"
}

Failed to start countdown for the second time during operation

I am using the following code and giving a second click to the same start countdown button not clean the first process, so there are two counts at the same time. How do I stop the first process when the second start?
Thank you very much in advance.
function countdown(element, minutes, seconds) {
// Fetch the display element
var el = document.getElementById(element);
// Set the timer
var interval = setInterval(function() {
if(seconds == 0) {
if(minutes == 0) {
(el.innerHTML = "STOP!");
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? '' : '';
el.innerHTML = minute_text + ' ' + seconds + ' ' + second_text + '';
seconds--;
}, 1000);
}
//Start as many timers as you want
var start1 = document.getElementById('timer1');
var start2 = document.getElementById('timer2');
start1.onclick = function() {
countdown('countdown1', 0, 15);
}
start2.onclick = function() {
countdown('countdown2', 0, 10);
}
//extra button and counter
<div id='countdown1'></div>
<div id='countdown2'></div>
<input id="timer1" type="button" value="Start timer 1" />
<input id="timer2" type="button" value="Start timer 2" />
You could save the interval variable as an attribute of the countdown element. Then, at the beginning of the countdown function, check if the interval attribute has been defined for that element. If so, call clearInterval on it before starting a new interval.
clearInterval(intervalvalue)
will be helpful to .
Working code here

How to make my button change once clicked to carry out a different function?

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;"...

how to make countdoun timer in java script which should not reset on page reload

i have used this code it working but when i refresh the page it reset to initial stage, i want it should continue after page reload also here is code i have used
<html>
<head>
<title>Timer</title>
</head>
<body>
<form name="counter"><input type="text" size="8" name="d2"></form>
<script>
<!--
//
var milisec=0
var seconds=30
document.counter.d2.value='30'
function display()
{
if (milisec<=0)
{
milisec=9
seconds-=1
}
if (seconds<=-1)
{
milisec=0
seconds+=1
}
else
milisec-=1
document.counter.d2.value=seconds+"."+milisec
setTimeout("display()",100)
}
display()
-->
</script>
</body>
</html>
You can save current seconds value in localStorage (or maybe sessionStorage) this is the easiest way to persist the value:
var milisec = 0
var seconds = localStorage.seconds || 30;
document.counter.d2.value = seconds;
function display() {
if (milisec <= 0) {
milisec = 9
seconds -= 1
}
if (seconds <= -1) {
milisec = 0
seconds += 1
} else milisec -= 1
localStorage.seconds = seconds;
document.counter.d2.value = seconds + "." + milisec;
if (seconds > 0 || (seconds == 0 && milisec > 0)) {
setTimeout(display, 100);
}
}
display();
Also note, that you probably want to stop interval when timer reaches 0 value, so I added seconds > 0 || (seconds == 0 && milisec > 0) part.
Demo: http://jsfiddle.net/6zL5eL2z/1/

Countdown timer on Label for 30 seconds using Javascript

I use the following example Redirect to redirect to a page. What i need is inside the image i would like to have a label or some text which should show count down from 30(secs) to 0(secs). I need javascript for this requirement.
Any help is appreciated
Hi include this before your existing DIV
<div id="myCounter">
</div>
Write the following Script
<script type="text/javascript">
var milisec = 0
var seconds = 30
document.getElementById("myCounter").innerHTML = '30';
function display() {
if (milisec <= 0) {
milisec = 9
seconds -= 1
}
if (seconds <= -1) {
milisec = 0
seconds += 1
}
else
milisec -= 1
document.getElementById("myCounter").innerHTML = seconds;
setTimeout("display()", 100)
}
display()
</script>
Adjust your DIV as per your need in the design by setting the position to absolute
<span id="myCounter"></span>
<script>
function counter (count) {
if (count > 0) {
document.getElementById("myCounter").innerHTML = count;
window.setTimeout(function() {counter(count-1)}, 1000);
} else {
window.location.href = "/redirected-page/";
}
}
counter(30);
</script>

Categories

Resources