HTML/JavaScript Countdown Timer - javascript

I have a countdown timer that currently allows the user to input a time and start the countdown from there.
I would like to have the text change colour after a certain amount of time, for example:
Text to go orange at 50%, then text to red when only 25% of the input time is left.
I'm pretty out of my depth already so would be very grateful for some detailed advice, thanks!
Here is my current code:
var secondsRemaining;
var intervalHandle;
function resetPage() {
document.getElementById('inputArea').style.display = 'block';
}
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0) {
alert('Countdown Finished!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
var minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
secondsRemaining = minutes * 60;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
}
window.onload = function() {
// create text input
var inputMinutes = document.createElement('input');
inputMinutes.setAttribute('id', 'minutes');
inputMinutes.setAttribute('type', 'text');
inputMinutes.setAttribute('placeholder', 'Enter Time');
//create button
var startButton = document.createElement('input');
startButton.setAttribute('type', 'button');
startButton.setAttribute('value', 'Start Countdown');
startButton.onclick = function() {
startCountdown();
};
// add to DOM
document.getElementById('inputArea').appendChild(inputMinutes);
document.getElementById('inputArea').appendChild(startButton);
}
html,
body {
font-family: helvetica;
color: #222;
background: #eaeaea;
margin: 0;
padding: 0;
box-sizing: border-box;
}
#container {
width: 400px;
margin: auto;
}
h1 {
font-size: 30em;
text-align: center;
margin: 40px 0;
padding: 0;
border-right: none;
border-left: none;
}
input {
display: block;
width: 80%;
border: 5px solid #E6E6E6;
background: #fff;
height: 50px;
margin-bottom: 5px;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
font-size: 19px;
text-align: center;
border-radius: 5px;
}
input[type=button] {
line-height: 30px;
font-size: 19px;
border: 2px solid #E6E6E6;
background: #f5b932;
color: #333;
font-weight: bold;
margin-top: 5px;
transition: .4s ease-in-out;
}
input[type=text]:focus {
outline: none;
}
input[type=button]:focus {
outline: none;
}
input[type=button]:hover {
background: #f5b934;
cursor: pointer;
}
.center-count {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 20vw;
}
<div id="container">
<div id="inputArea"></div>
</div>
<br>
<br>
<br>
<h1 id="time">0:00</h1>

Try this:
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//Convert remaining seconds to presentage of total seconds
precentageS = Math.floor(secondsRemaining/totalSeconds)*100
//Change color based on persentage
if(precentageS <= 50){
document.getElementById("time").style.color = "orange";
}else if(precentageS <= 25){
document.getElementById("time").style.color = "red";
}else{
document.getElementById("time").style.color = "blue";
}
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
//stop if down to zero
if (secondsRemaining === 0) {
alert('Countdown Finished!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
var minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
secondsRemaining = minutes * 60;
totalSeconds = secondsRemaining;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
}
What I've done is added a totalSeconds variable after the secondsRemaining so I can keep track of how many seconds we started with. I then convert the secondsRemaining into a percentage of the totalSeconds And have if statements depending on the number of times you would like to change color.

Try something like this:
Extracted minutes to be able to calculate percentage on the run.
Added two condition to change color...
var secondsRemaining;
var intervalHandle;
// Total time
var minutes;
function resetPage() {
document.getElementById('inputArea').style.display = 'block';
}
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
// Change color by percentage
// Below 25% = 60 / 4 : red
if (secondsRemaining < minutes * 15) {
timeDisplay.style.color = "red";
}
// Below 50% = 60 / 2 : orange
else if (secondsRemaining < minutes * 30) {
timeDisplay.style.color = "orange";
}
//stop if down to zero
if (secondsRemaining === 0) {
alert('Countdown Finished!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
secondsRemaining = minutes * 60;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
}
window.onload = function() {
// create text input
var inputMinutes = document.createElement('input');
inputMinutes.setAttribute('id', 'minutes');
inputMinutes.setAttribute('type', 'text');
inputMinutes.setAttribute('placeholder', 'Enter Time');
//create button
var startButton = document.createElement('input');
startButton.setAttribute('type', 'button');
startButton.setAttribute('value', 'Start Countdown');
startButton.onclick = function() {
startCountdown();
};
// add to DOM
document.getElementById('inputArea').appendChild(inputMinutes);
document.getElementById('inputArea').appendChild(startButton);
}
html,
body {
font-family: helvetica;
color: #222;
background: #eaeaea;
margin: 0;
padding: 0;
box-sizing: border-box;
}
#container {
width: 400px;
margin: auto;
}
h1 {
font-size: 30em;
text-align: center;
margin: 40px 0;
padding: 0;
border-right: none;
border-left: none;
}
input {
display: block;
width: 80%;
border: 5px solid #E6E6E6;
background: #fff;
height: 50px;
margin-bottom: 5px;
margin-top: 10px;
margin-left: auto;
margin-right: auto;
font-size: 19px;
text-align: center;
border-radius: 5px;
}
input[type=button] {
line-height: 30px;
font-size: 19px;
border: 2px solid #E6E6E6;
background: #f5b932;
color: #333;
font-weight: bold;
margin-top: 5px;
transition: .4s ease-in-out;
}
input[type=text]:focus {
outline: none;
}
input[type=button]:focus {
outline: none;
}
input[type=button]:hover {
background: #f5b934;
cursor: pointer;
}
.center-count {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
height: 20vw;
}
<div id="container">
<div id="inputArea"></div>
</div>
<br>
<br>
<br>
<h1 id="time">0:00</h1>

I would go with a percentage approach, here's your code with that verification.
Set a new variable for initialTime asked.
var initialTime;
var secondsRemaining;
var intervalHandle;
function resetPage() {
document.getElementById('inputArea').style.display = 'block';
}
function tick() {
//grab h1
var timeDisplay = document.getElementById('time');
//turn seconds into mm:55
var min = Math.floor(secondsRemaining / 60);
var sec = secondsRemaining - (min * 60);
//add leading 0 if seconds less than 10
if (sec < 10) {
sec = '0' + sec;
}
//concatenate with colon
var message = min.toString() + ':' + sec;
// now change the display
timeDisplay.innerHTML = message;
Then on each tick, check what's the actual percentage left on the counter.
var remainingPercentage = secondsRemaining*100/initialTime;
if (remainingPercentage === 75) {
timeDisplay.style.color = "orange";
}
if (remainingPercentage === 50) {
timeDisplay.style.color = "yellow";
}
if (remainingPercentage === 25) {
timeDisplay.style.color = "red";
}
//stop if down to zero
if (secondsRemaining === 0) {
alert('Countdown Finished!');
clearInterval(intervalHandle);
resetPage();
}
// subtract from seconds remaining
secondsRemaining--;
}
function startCountdown() {
//get contents
var minutes = document.getElementById('minutes').value;
//check if not a number
if (isNaN(minutes)) {
alert("Please enter a number!");
return;
}
//how many seconds?
When first setting secondsRemaining, store it in initialTime too.
secondsRemaining = initialTime = minutes * 60;
//call tick
intervalHandle = setInterval(tick, 1000);
//hide form
document.getElementById('inputArea').style.display = 'none';
}
window.onload = function() {
// create text input
var inputMinutes = document.createElement('input');
inputMinutes.setAttribute('id', 'minutes');
inputMinutes.setAttribute('type', 'text');
inputMinutes.setAttribute('placeholder', 'Enter Time');
//create button
var startButton = document.createElement('input');
startButton.setAttribute('type', 'button');
startButton.setAttribute('value', 'Start Countdown');
startButton.onclick = function() {
startCountdown();
};
// add to DOM
document.getElementById('inputArea').appendChild(inputMinutes);
document.getElementById('inputArea').appendChild(startButton);
}

Related

Why the div is not moving leftwards using "right" ? in third step

Here, I have code a program that revolves the targeted div in a rectangular path using CSS positions properties in setInterval() method.
Firstly, the div indeed moves rightwards (using left CSS property) and then downwards (using top CSS property) but when the thirds step comes it doesn't move leftwards (using CSS right property). Why is that so?
let a = 0;
let node = document.querySelector(".node");
let inter1 = setInterval(function() {
if (a == 260) {
clearInterval(inter1);
a = 0;
let inter2 = setInterval(function() {
if (a == 639) {
clearInterval(inter2);
a = 260;
let inter3 = setInterval(function() {
if (a == 0) {
clearInterval(inter3);
} else {
a -= 1;
node.style.right = a + "px";
}
}, 1)
} else {
a += 1;
node.style.top = a + "px";
}
}, 1)
} else {
a += 1;
node.style.left = a + "px";
}
}, 1)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: serif;
}
body {
background: black;
color: white;
width: 100vw;
}
.node {
background: dodgerblue;
color: white;
display: inline-block;
width: 100px;
height: 100px;
position: absolute;
}
<div class="node"></div>
Like the user #JavaScript wrote, you should decide for one - left or right.
Therefor you could change right to left in the inter3 statement:
let inter3 = setInterval(function() {
if (a == 0) {
clearInterval(inter3);
} else {
a -= 1;
node.style.left = a + "px";
}
}, 1);
let a = 0;
let node = document.querySelector(".node");
let inter1 = setInterval(function() {
if (a == 260) {
clearInterval(inter1);
a = 0;
let inter2 = setInterval(function() {
if (a == 639) {
clearInterval(inter2);
a = 260;
let inter3 = setInterval(function() {
if (a == 0) {
clearInterval(inter3);
} else {
a -= 1;
node.style.left = a + "px";
}
}, 1)
} else {
a += 1;
node.style.top = a + "px";
}
}, 1)
} else {
a += 1;
node.style.left = a + "px";
}
}, 1)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: serif;
}
body {
background: black;
color: white;
width: 100vw;
}
.node {
background: dodgerblue;
color: white;
display: inline-block;
width: 100px;
height: 100px;
position: absolute;
}
<div class="node"></div>

Opposing condition for a div

I need to make a ball grow until it reaches 400, which thereafter it would shrink the same way. Would really appreciate feedback what I'm doing wrong in my code:
var
ball1Size = 100
, ball2Size = 100
, ball2SizeStep = 50
;
function onBall2Click()
{
var ball2 = document.querySelector('.ball2');
ball2Size = ball2Size + 50;
if (ball2Size > 400) {
ball2Size = ball2Size - 100;
}
else {
ball2Size - 150;
}
ball2.innerText = ball2Size;
ball2.style.width = ball2Size;
ball2.style.height = ball2Size;
}
body {
background-color : black;
text-align : center;
}
h1 {
color : white;
}
div {
width : 100px;
height : 100px;
margin : auto;
margin-bottom : 10px;
border-radius : 50%;
transition : 0.3s;
line-height : 50px;
}
.ball2 {
background-color : orange;
}
<div class="ball2" onclick="onBall2Click()">
SIZE
</div>
See code fix and syntax fixes
here:
var ball1Size = 100;
var ball2Size = 100;
var ball2SizeStep = 50;
function onBall2Click() {
var ball2 = document.querySelector('.ball2');
ball2Size = ball2Size + ball2SizeStep;
if (ball2Size >= 400) {
ball2SizeStep = -50
} else if (ball2Size <= 50) {
ball2SizeStep = 50
}
ball2.innerText = ball2Size;
ball2.style.width = ball2Size + "px";
ball2.style.height = ball2Size + "px";
}
body {
background-color: black;
text-align: center;
}
h1 {
color: white;
}
div {
width: 100px;
height: 100px;
margin: auto;
margin-bottom: 10px;
border-radius: 50%;
transition: 0.3s;
line-height: 50px;
}
.ball2 {
background-color: orange;
}
<div class="ball2" onclick="onBall2Click()" >
SIZE
</div>
This is what you want to do, increase the balls size for each click that it can be increased for, i.e., is under 400, when it reaches 400, decrease the ball size for each click until it reaches its original size. Rinse and repeat.
var ball1Size = 100;
var ball2Size = 100;
var ball2SizeStep = 50;
let isBallDecreasing = false;
function onBall2Click() {
var ball2 = document.querySelector('.ball2');
if (ball2Size === 100) isBallDecreasing = false;
if (ball2Size >= 400 || isBallDecreasing) {
ball2Size -= 50;
isBallDecreasing = true;
} else {
ball2Size += 50
isBallDecreasing = false;
}
ball2.innerText = ball2Size;
ball2.style.width = ball2Size;
ball2.style.height = ball2Size
}
<div class="ball2" onclick="onBall2Click()">
SIZE
</div>
Using a boolean to track the direction can simplify it
let direction = 1;
const min = 100;
const max = 400;
const step = 50;
let current = 100;
var ball = document.querySelector(".ball2");
ball.addEventListener("click", function() {
current += direction * step;
if (current >= max) {
current = max;
direction = -1;
} else if (current <= min) {
current = min;
direction = 1;
}
updateElem();
});
function updateElem() {
ball.textContent = current;
ball.style.width = current + 'px';
ball.style.height = current + 'px';
}
updateElem();
body {
background-color: black;
text-align: center;
}
h1 {
color: white;
}
.ball {
width: 100px;
height: 100px;
margin: auto;
margin-bottom: 10px;
border-radius: 50%;
transition: 0.3s;
line-height: 50px;
}
.ball2 {
background-color: orange;
}
<div class="ball ball2">
SIZE
</div>
If you are going to have more than one of these you probably want to have some sort of way to keep track. Using data attributes can help out so you do not need more than one copy of the code.
document.querySelectorAll(".ball2").forEach(function (ball) {
ball.addEventListener("click", function () {
let direction = +ball.dataset.direction;
const min = +ball.dataset.min;
const max = +ball.dataset.max;
const step = +ball.dataset.step;
const current = +ball.dataset.current;
let updated = current + direction * step;
if (updated >= max) {
updated = max;
direction = -1;
} else if (updated <=min) {
updated = min;
direction = 1;
}
updateElem();
ball.dataset.direction = direction;
ball.dataset.current = updated;
});
function updateElem() {
const num = ball.dataset.current;
ball.textContent = num;
ball.style.width = num + 'px';
ball.style.height = num + 'px';
}
updateElem();
});
body {
background-color: black;
text-align: center;
}
h1 {
color: white;
}
.ball {
width: 100px;
height: 100px;
margin: auto;
margin-bottom: 10px;
border-radius: 50%;
transition: 0.3s;
line-height: 50px;
}
.ball2 {
background-color: orange;
}
<div
class="ball ball2"
data-direction="1"
data-min="100"
data-max="400"
data-step="50"
data-current="100">
SIZE
</div>
<div
class="ball ball2"
data-direction="-1"
data-min="100"
data-max="400"
data-step="50"
data-current="400">
SIZE
</div>
<div
class="ball ball2"
data-direction="1"
data-min="0"
data-max="1000"
data-step="100"
data-current="200">
SIZE
</div>
you can also Use CSS custom properties for simplifying your code:
const ball2 = document.querySelector('.ball2');
var
ballSz = 100
, ball2SizeStep = 50
;
ball2.onclick =()=>
{
ballSz += ball2SizeStep
ball2.textContent = ballSz
ball2.style.setProperty('--szHW', ballSz + 'px')
if (ballSz >= 400) ball2SizeStep = -50
if (ballSz <= 100) ball2SizeStep = +50
}
body {
background-color : black;
text-align : center;
}
h1 {
color : white;
}
div {
--szHW : 100px; /* <--- CSS custom properties */
width : var(--szHW);
height : var(--szHW);
margin : auto;
margin-bottom : 10px;
border-radius : 50%;
transition : 0.3s;
line-height : 50px;
}
.ball2 {
background-color : orange;
}
<div class="ball2">
SIZE
</div>
the same, for multiples balls
document.querySelectorAll('.ball2').forEach( ball2 =>
{
ball2.style.setProperty('--szHW', ball2.dataset.size + 'px') // init sizes according to data-size value
ball2.onclick =_=>
{
let
min = Number(ball2.dataset.min)
, max = Number(ball2.dataset.max)
, step = Number(ball2.dataset.step)
, size = Number(ball2.dataset.size)
;
if ( size === min && step < 0
|| size === max && step > 0 )
{
step *= -1
ball2.dataset.step = step
}
ball2.dataset.size = size += step
ball2.style.setProperty('--szHW', size + 'px')
}
})
body {
background-color : black;
text-align : center;
}
div.ball2 {
--szHW : 100px; /* <--- CSS custom properties */
width : var(--szHW);
height : var(--szHW);
margin : auto;
margin-bottom : 10px;
border-radius : 50%;
transition : 0.3s;
line-height : 50px;
background : orange;
}
div.ball2::before {
content: attr(data-size)
}
<div class="ball2" data-min="100" data-max="400" data-step="50" data-size="100"></div>
<div class="ball2" data-min="100" data-max="400" data-step="50" data-size="400"></div>
<div class="ball2" data-min="100" data-max="1000" data-step="100" data-size="200"></div>

Javascript date countdown with custom date

var timer;
var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));
timer = setInterval(function() {
timeBetweenDates(compareDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = toDate;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
}
body {
background: #f5f5f5;
}
#timer {
font-family: Arial, sans-serif;
font-size: 20px;
color: #999;
letter-spacing: -1px;
}
#timer span {
font-size: 60px;
color: #333;
margin: 0 3px 0 15px;
}
#timer span:first-child {
margin-left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">
<span id="days"></span>days
<span id="hours"></span>hours
<span id="minutes"></span>minutes
<span id="seconds"></span>seconds
</div>
setDate() sets only Day of the current month in date object. You can directly provide your date string in YYYY-MM-DD format to Date() while creating new object.
var timer;
var compareDate = new Date('2020-06-02');
// compareDate.setDate(Date.parse('2020-06-02'));
timer = setInterval(function() {
timeBetweenDates(compareDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = toDate;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
}
body {
background: #f5f5f5;
}
#timer {
font-family: Arial, sans-serif;
font-size: 20px;
color: #999;
letter-spacing: -1px;
}
#timer span {
font-size: 60px;
color: #333;
margin: 0 3px 0 15px;
}
#timer span:first-child {
margin-left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">
<span id="days"></span>days
<span id="hours"></span>hours
<span id="minutes"></span>minutes
<span id="seconds"></span>seconds
</div>
Directly set new Date()
var compareDate = new Date('2020-06-02');
Change
var compareDate = new Date();
compareDate.setDate(Date.parse('2020-06-02'));
to
var compareDate = new Date(2020, 05, 2);

Can not get value inside loop using pure JavaScript

Why I cannot get value inside the loop
Can use javascript only
Pause text for 2000ms on hover
reverse work on hover but should pause it first and then reverse the sequence until mouse out.
loop on reading text from textarea "input"
find this line in javascript to control delay
if(document.getElementById('flag2').value == "0"){
/*
1 : center
2 - 4 : center 2
5 - 7 : center 3
8 - 10 : center 4
11 - 13 : center 5
14 - 16 : center 6
17 - 19 : center 7
*/
stopNow= false;
function Loop(txt, wpm) {
txt = txt.replace(/\n/g, ' ');
var a = txt.split(' '),
n = a.length,
i = 0,
b = document.getElementById('bw'),
tw = document.getElementById('tw'),
tx = {
L: document.getElementById('txt_L'),
C: document.getElementById('txt_C'),
R: document.getElementById('txt_R')
}
;
function width(w) {
tw.textContent = w;
return tw.offsetWidth;
}
function middle(w) {
var x = 0;
var n = w.length,
// Center char calculation. 1=1, 2-4=2, 5-7=3, ...
c = ~~((n + 1) / 3) + 1,
z = {};
if (!n)
return;
z.a = width(w.substr(0, c - 1));
z.b = width(w.substr(0, c));
z.c = (z.b - z.a) / 2;
b.style.paddingLeft = ~~(110 - (z.a + z.c)) + 'px';
tx.L.textContent = w.substr(0, c - 1);
tx.C.textContent = w.substr(c - 1, 1);
tx.R.textContent = w.substr(c);
}
function word() {
if(stopNow){
middle(a[i])
if (--i === n)
i = 0;
return 0;
}
else{
middle(a[i])
if (++i === n)
i = 0;
return 0;
}
}
this.whiteout = function(w) {
if (w) {
tx.L.style.color = '#fff';
tx.R.style.color = '#fff';
} else {
tx.L.style.color = '#080';
tx.R.style.color = '#000';
}
};
wpm = wpm || 200;
var __time = 2000;
//can not get changes value here
if(document.getElementById('flag2').value == "0"){
__time = (60/wpm) * 1000;}
document.getElementById('flag1').innerHTML += document.getElementById('flag2').innerHTML ;
var tt = setInterval(function (){
document.getElementById('flag1').innerHTML = word();
}, __time);
}
var txt = document.getElementById('input').value;
var ww = new Loop(txt, 250);
document.getElementById('bw').addEventListener('change', function() {
ww.whiteout(this.checked);
});
document.getElementById('txtHolder').addEventListener('mouseover', function () {
stopNow = true;
document.getElementById('flag2').innerHTML = "1";
});
document.getElementById('txtHolder').addEventListener('mouseout', function () {
stopNow = false;
document.getElementById('flag2').innerHTML = "0";
});
* {
padding: 0;
margin:0;
}
.hide {
display: none;
}
#tw {
position: absolute;
visibility: hidden;
white-space: nowrap;
}
#tw,
#txt_L,
#txt_C,
#txt_R
{
font: bold 18px Arial;
line-height: 1;
}
#txt_L { color: #000; }
#txt_C { color: #f00; }
#txt_R { color: #000; }
#wrap {
position: relative;
width: 220px;
height: 50px;
border-top: 1px solid #000;
border-bottom: 1px solid #000;
}
#b1 {
width: 110px;
height: 50px;
border-right: 1px solid #000;
float:left;
}
#bw {
position: absolute;
width: 220px;
top: 10px;
background: #fff;
padding: 5px 0;
line-height: 1;
vertical-align: middle;
}
<!--
EXTRA POINTS---------
Pause text for 2000ms on hover and reverse the sequence until mouse out.
-->
<div id="flag1">
</div>
<div id="flag2">
</div>
<div id="txtHolder">
<span id="tw"></span>
<div id="wrap">
<div id="b1"></div>
<div id="bw"><span id="txt_L"> </span><span id="txt_C"></span><span id="txt_R"></span></div>
</div>
</div>
<textarea id="input" class="hide">
Oh, hey there, TIDWRTWHUFOO fans. Thinking about going for a little dip this summer? How about you go for a swim with a one-ton crab that will smash you under its massive legs? Sound fun? Definitely!
Crabster is a wild crab-like robot designed to explore the deepest oceans without smashing itself into a squashed tin can. It has massive legs, a large body, and lots of cameras so it can find you even if you’re the dude from The Big Blue and can dive really deep. There’s no escaping our future robotic-aquatic overlords
</textarea>

Where should I need to put replaceChild() so it replace existing div

I am new to programming and recently started learning JavaScript. I made a little program that take HSL color value and show all saturation values of that color. Currently when user enter the input value second or third time it creates a new div (Try to enter a value second or third time in JSFiddle example). What I want is that when user enter the value second or third time instead of creating a new div every time it should replace the existing div. I am familiar with replaceChild() method but not sure where it should be placed.
Here is my code:
var satInput = document.createElement("input");
var satButton = document.createElement("button");
satInput.setAttribute("placeholder", "Write a number between 0 to 360");
satInput.setAttribute("size", "30")
satButton.innerHTML = "Submit";
document.body.appendChild(satInput);
document.body.appendChild(satButton);
var saturation = function() {
if (satInput.value !== "" && satInput.value >= 0 && satInput.value <= 360) {
var background = document.createElement("div");
background.id = "bg";
document.body.appendChild(background);
for (var i = 0; i <= 100; i++) {
var childDiv = document.createElement("div");
childDiv.id = "color";
background.appendChild(childDiv);
childDiv.style.backgroundColor = "hsl(" + satInput.value + "," + i + "%, 50%)";
}
} else {
alert("Please write a number between 0 to 360.");
}
}
satButton.onclick = saturation;
One way is to replace the bg div, if it exists
var satInput = document.createElement("input");
var satButton = document.createElement("button");
satInput.setAttribute("placeholder", "Write a number between 0 to 360");
satInput.setAttribute("size", "30")
satButton.innerHTML = "Submit";
document.body.appendChild(satInput);
document.body.appendChild(satButton);
var saturation = function() {
if (satInput.value !== "" && satInput.value >= 0 && satInput.value <= 360) {
var existing = document.getElementById("bg");
var background = document.createElement("div");
background.id = "bg";
if (existing) {
document.body.replaceChild(background, existing);
} else {
document.body.appendChild(background);
}
for (var i = 0; i <= 100; i++) {
var childDiv = document.createElement("div");
childDiv.id = "color";
background.appendChild(childDiv);
childDiv.style.backgroundColor = "hsl(" + satInput.value + "," + i + "%, 50%)";
}
} else {
alert("Please write a number between 0 to 360.");
}
}
satButton.onclick = saturation;
#bg {
background-color: #eee;
border: 1px solid #000;
text-align: center;
padding: 10px 0;
margin-top: 10px;
}
#color {
display: inline-block;
height: 20px;
width: 15%;
border: 1px solid #000;
margin: 2px;
text-align: center;
font-family: segoe, sans-serif;
font-size: 14px;
line-height: 18px;
}
Another is just to remove the contents of bg and then add the new content
var satInput = document.createElement("input");
var satButton = document.createElement("button");
satInput.setAttribute("placeholder", "Write a number between 0 to 360");
satInput.setAttribute("size", "30")
satButton.innerHTML = "Submit";
document.body.appendChild(satInput);
document.body.appendChild(satButton);
var saturation = function() {
if (satInput.value !== "" && satInput.value >= 0 && satInput.value <= 360) {
var background = document.getElementById("bg");
if (background) {
background.innerHTML = '';
} else {
background = document.createElement("div");
document.body.appendChild(background);
background.id = "bg";
}
for (var i = 0; i <= 100; i++) {
var childDiv = document.createElement("div");
childDiv.id = "color";
background.appendChild(childDiv);
childDiv.style.backgroundColor = "hsl(" + satInput.value + "," + i + "%, 50%)";
}
} else {
alert("Please write a number between 0 to 360.");
}
}
satButton.onclick = saturation;
#bg {
background-color: #eee;
border: 1px solid #000;
text-align: center;
padding: 10px 0;
margin-top: 10px;
}
#color {
display: inline-block;
height: 20px;
width: 15%;
border: 1px solid #000;
margin: 2px;
text-align: center;
font-family: segoe, sans-serif;
font-size: 14px;
line-height: 18px;
}

Categories