Make countdown start after button is clicked - javascript

I'm creating a kid's game with a timer countdown that starts after the user clicks a button.
The code I'm using initiates the countdown without a problem, but I'd like the countdown to start only after the button is clicked.
Here is my code:
window.onload = function(){
(function(){
var counter = 5;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
})();
}
JSFiddle
Thank you!
Lauren

Use click event of action link with id= "startClock"
$("#startClock").click( function(){
var counter = 5;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
});

Create a function and add click lister to button to call that function. Do somthing like this.
function startTimer(){
var counter = 5;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
}
function start()
{
document.getElementById("count").style="color:green;";
startTimer();
};
button
{
font-size:40px;
background-color:black;
color:white;
}
#count
{
margin-left:20px;
font-size:30px;
color:black;
}
<span id="count">5</span> seconds
<br>
<button onclick="start()">
START
</button>

Use on method $(selector).on('click',callback);

You are expecting the function get work when you click and in your code you are using onload event.
So use click() event of jQuery for your requirement.
$('#startClock').click(function(){
var counter = 5;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
});

I just want to suggest you to put it in click handler of your selector instead of doing that on window load:
jQuery(function($){
$('#startClock').on('click', doCount);
});
function doCount(){
var counter = 5;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
}
Demo # Fiddle
Also i need to suggest you that to use $(function(){}); dom ready function instead of window.onload = function(){}; just because dom ready does not wait for dom to get fully loaded to execute the script.

You are attaching your function in onLoad of the page, instead attach onClick
#count
{
font-size:30px;
color:green;
font-weight:bolder;
text-shadow:1px 1px 1px blue;
}
#text
{
font-size:30px;
color:blue;
font-weight:bolder;
}
button
{
font-size:25px;
background:black;
color:white;
border-radius:20px;
}
button:hover
{
transition:0.3s linear;
font-size:29px;
background:purple;
color:aliceblue;
border-radius:15px;
}
<span id="count">5</span> <span id="text">seconds</span>
<button onclick="start()">Start Clock</button>
<script>
function start(){
var counter = 5;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
};
</script>

Related

How to prevent setInterval from being called multiple times simultaneously?

Is there a way to make the setInterval work only once at a time?
My code should work this way:
You manually input the number of the seconds;
The "div" works as a timer and runs till reaching 0.
If you click "Click me" once, it will work as expected.
However, if you click the button multiple times fast enough, the even listener will be working simultaneously as many times as you clicked.
let button = document.getElementById('button');
let input = document.getElementById('input');
let timer = document.getElementById('timer');
function timerRunner () {
let startTime = input.value;
if (startTime <= 0) {
console.log('The number is <=0')
} else {
do {
timer.textContent = startTime;
let counter = startTime;
let interval = setInterval(()=> {
console.log(counter);
counter--;
timer.textContent = counter;
if (counter === 0) {
clearInterval(interval);
}
}, 1000);
} while (typeof (timer.textContent) == "number");
}
}
button.addEventListener('click', timerRunner)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.centeralizer {
display: block;
width: 200px;
margin: 20vh auto;
}
#input {
display: block;
margin-bottom: 35px;
width: 150px;
}
#button {
display: inline-block;
margin-right: 35%;
}
#timer {
display: inline-block;
}
</style>
<script src="index.js" defer></script>
</head>
<body>
<div class="centeralizer">
<input id="input" placeholder="Input the number" type="number">
<button id="button">Click me</button>
<div id="timer">0</div>
</div>
</body>
</html>
You should store the running interval in the upper scope and clear it if the button is pressed again.
const button = document.getElementById('button');
const input = document.getElementById('input');
const timer = document.getElementById('timer');
let interval = null;
function startTimer() {
const startTime = +input.value;
if (startTime <= 0) {
console.log('The number is <= 0');
return;
}
let counter = startTime;
timer.textContent = startTime;
if (interval) clearInterval(interval);
interval = setInterval(() => {
timer.textContent = --counter;
console.log(counter);
if (counter === 0) clearInterval(interval);
}, 1000);
}
button.addEventListener('click', startTimer)
You can add a boolean variable isRunning that tracks whether the timer is running. You set it on when the timer is running and set it off when the timer is done. Check if it's on when the button is clicked, and return if it is. You can prevent multiple instances of the timer being triggered.
let button = document.getElementById('button');
let input = document.getElementById('input');
let timer = document.getElementById('timer');
var isRunning = false;
function timerRunner () {
if(isRunning) {
return; //return if timer is already running
}
isRunning = true; //specify that the timer is running
let startTime = input.value;
if (startTime <= 0) {
console.log('The number is <=0')
} else {
do {
timer.textContent = startTime;
let counter = startTime;
let interval = setInterval(()=> {
console.log(counter);
counter--;
timer.textContent = counter;
if (counter === 0) {
isRunning = false; //specify that the timer is not running and can be run again
clearInterval(interval);
}
}, 1000);
} while (typeof (timer.textContent) == "number");
}
}
button.addEventListener('click', timerRunner)

How to make a click on the button change its color in Javascript

I am making a small game where in I have 50 buttons and when I click on any one of the button, its color changes and amongst them, I have one button which is blue in color. If the player clicks on that blue button, he is a winner. He will be given only three chances. I have used a button eventhandler that takes the color id and accordingly changes the color. But the colorId from the count is 51 and not amongst the 1 - 50 buttons. What is wrong?
<html>
<head>
<title>Blue-Box</title>
</head>
<body>
<script>
var colorId;
var button;
var noOfTries = 3;
function createButtons() {
colorId = 0;
for (var index = 0; index <= 50; index++) {
button = document.createElement("button");
button.innerHTML = "box " + index;
button.id = colorId;
button.setAttribute("value", colorId);
button.setAttribute("text", colorId);
button.style.fontFamily = "Times New Roman";
button.style.backgroundColor = "#C0C0C0";
button.style.fontSize = "15px";
document.body.appendChild(button);
colorId++;
button.addEventListener("click", selectColor);
}
}
function selectColor() {
console.log((colorId));
console.log("button click");
if (noOfTries > 0) {
noOfTries = noOfTries - 1;
if ((colorId) <= 24) {
console.log("red color")
document.getElementById(colorId).style.backgroundColor = "#BC8F8F";
}
else if (colorId == 25) {
console.log("blue color")
document.getElementById(colorId).style.backgroundColor = "#0099CC";
document.write("You Won the game");
noOfTries = 3;
}
else if (colorId > 25 && colorId < 51) {
document.getElementById(colorId).style.backgroundColor = "#008080";
}
}
else {
document.write("Your attempts have finished");
}
}
</script>
<div id="divbox">
<button id="buttonbox" onclick="createButtons()">Click to start the Game</button>
</div>
</body>
</html>
Hope this helps you.
<html>
<head>
<title>Blue-Box</title>
</head>
<body>
<script>
var colorId = 1;
var button;
var lives = 0;
function createButtons(){
colorId=0;
for(var index=1;index<=50;index++){
button=document.createElement("button");
button.innerHTML="box "+index;
button.id=colorId;
button.setAttribute("value",colorId);
button.setAttribute("text",colorId);
button.style.fontFamily="Times New Roman";
button.style.backgroundColor="#C0C0C0";
button.style.fontSize="15px";
button.addEventListener("click", function(){
selectColor(this.id);
})
document.getElementById("btnbox").appendChild(button);
colorId++;
}
}
function selectColor(colorId){
lives++;
if(lives < 4){
if (colorId<=24){
document.getElementById(colorId).style.backgroundColor="#BC8F8F";
}
else if (colorId==25){
document.getElementById(colorId).style.backgroundColor="#0099CC";
alert("Winner");
location.reload();
}
else{
document.getElementById(colorId).style.backgroundColor="limegreen";
}
}
else if(lives == 4){
alert("Game over!");
location.reload();
}
}
</script>
<div id="divbox">
<button id="buttonbox" onclick="createButtons()">Click to start the Game</button>
</div>
<div id="btnbox">
</div>
</body>
// first add a global variable
var noOfTries = 3;
function selectColor() {
// check if greater than 3
if(noOfTries > 0) {
// if yes, then decrement
noOfTries = noOfTries - 1;
// continue with the color change
if (colorId<=24) {
document.getElementById(colorId).style.backgroundColor="#BC8F8F";
}
else if (colorId==25) {
document.getElementById(colorId).style.backgroundColor="#0099CC";
}
else {
document.getElementById(colorId).style.backgroundColor="limegreen";
}
}
}
Use:
button.addEventListner("click",function() {
button.style.backgroundColor=nextColor;
})

How to not increase setInterval then called several times

Is there is possibility to not increase set interval speed after calling it several times. I'm doing the auto scroll function. After you hit the selected speed button it calls the function setInterval. My problem that more I hit button page scrolls faster and faster. how to solve my logical mistake?
function scroll() {
var scrollspeed = document.getElementById("scrollspeedval").value;
if (scrollspeed == 1) {
window.scrollBy(0, 1);
} else if (scrollspeed == 2) {
window.scrollBy(0, 2);
} else if (scrollspeed == 3) {
window.scrollBy(0, 4);
} else if (scrollspeed == 4) {
window.scrollBy(0, 8);
} else if (scrollspeed == 5) {
window.scrollBy(0, 12);
} else if (scrollspeed == 0) {
};
}
$("document").ready(function() {
$(".scrollcl").click(function() {
var interval_for_autoscroll = setInterval(function() {
scroll();
}, 400);
});
});
You should stop the already running interval timer using clearInterval before starting the new one:
clearInterval(interval_for_autoscroll); // where interval_for_autoscroll is declared outside the scope of the callback.
Something like this:
function scroll() {
var $object = $('.object'),
angle = $object.data('angle') || 0;
$object
.css({ 'transform': 'rotateZ(' + angle + 'deg)' })
.data('angle', (angle + 10) % 360);
}
$("document").ready(function() {
var interval_for_autoscroll;
$('.slow').click(function() {
clearInterval(interval_for_autoscroll);
interval_for_autoscroll = setInterval(scroll.bind(window), 400);
});
$('.normal').click(function() {
clearInterval(interval_for_autoscroll);
interval_for_autoscroll = setInterval(scroll.bind(window), 100);
});
$('.fast').click(function() {
clearInterval(interval_for_autoscroll);
interval_for_autoscroll = setInterval(scroll.bind(window), 10);
});
});
.object {
display: inline-block;
width: 100px;
height: 50px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="object">
</div>
<button class="slow">slow</button>
<button class="normal">normal</button>
<button class="fast">fast</button>
Seeing as you're using JQuery, I suppose .one() might be a better option for you, if you only want the event to trigger once.
You could try something like this:
$(".scrollcl").one("click",function(){});

How to add fade in and fade out when changing between texts in javascript

I have below my JAVASCRIPT code which change between 2 words every 2.5 seconds and I want to add fading to the transition between the words in the array it uses. I know that I need to use Jquery but how do I implement it in this recursive function? Any ideas?
var text = ["first", "second"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 2500);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
}
}
.banner-right h2 {
font-size: 50px;
font-weight: 300;
color: #ffffff;
margin: 15px 0 45px 0;
}
<h2 id="changeText">Data Scientist</h2>
Since you are using Native JavaScript you could use CSS transitions and classList.
Something like:
CSS
#changeText {
opacity: 1;
transition: opacity 0.5s;
}
.hide {
opacity: 0 !important;
}
JavaScript
function change() {
elem.classList.add('hide');
setTimeout(function () {
elem.innerHTML = text[counter];
elem.classList.remove('hide');
counter++;
if (counter >= text.length) {
counter = 0;
}
}, 500);
}
Demo:
var text = ["first", "second"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 2500);
function change() {
elem.classList.add('hide');
setTimeout(function () {
elem.innerHTML = text[counter];
elem.classList.remove('hide');
counter++;
if (counter >= text.length) {
counter = 0;
}
}, 500);
}
#changeText {
opacity: 1;
transition: opacity 0.5s;
}
.hide {
opacity: 0 !important;
}
<h2 id="changeText">Data Scientist</h2>
Note: I used !important in the CSS because opacity: 1; when applied with a ID selector has priority over a class selector.
Replace this part:
elem.innerHTML = text[counter];
With:
$(elem)
.fadeOut(400)
.html(text[counter])
.delay(400)
.fadeIn(400);

Change div's hover state with jQuery timer

I’m a complete jquery newb and I want to create 5 classes(.button1 - .button5) with a timer which toggles the next classes :hover or :active state every 4000ms on a continuous loop. I also want the ability for the timer to halt and continue if another one of the classes is hovered on by the user. Does anyone know of a good starting point or a thread with a similar solution?
I’ve attached a diagram.
CSS
.wrapper { width:100%; margin:0 auto; background:#f3f3f3; }
#buttonblock { display:block; }
.button1, .button2, .button3, .button4, .button5 { display:inline-block; margin:0 5px; height:50px; width:50px; border-radius:25px; background:#3cc8dd; }
.button1:hover, .button2:hover, .button3:hover, .button4:hover, .button5:hover{ background:#fbc040; }
HTML
<div class="wrapper">
<div id="buttonblock">
<div class="button1"></div>
<div class="button2"></div>
<div class="button3"></div>
<div class="button4"></div>
<div class="button5"></div>
</div>
</div>
you can simply loop over the array of objects, for example
var $block = $('#buttonblock div');
for (var n=0; n<$block.length; n++)
{
var domELM = $block[n]; // you can do $(domELM) to create a jquery of the dom
// do stuff here, set interval or whatever it is you wish to do.
if(n == $block.elngth)
n=0; //resets the loop
}
HTML
<div class="wrapper">
<div id="buttonblock">
<div class="button button1"></div>
<div class="button button2"></div>
<div class="button button3"></div>
<div class="button button4"></div>
<div class="button button5"></div>
</div>
css
.hover {
background:#fbc040;
}
js
var counter = 1;
var timer;
$(document).ready(function () {
startTimer();
$('.button').mouseenter(function () {
$('.hover').removeClass('hover');
clearInterval(timer);
});
$('.button').mouseleave(function () {
startTimer();
});
});
function startTimer() {
timer = setInterval(function () {
counter = (counter > 5) ? 1 : counter;
$('.hover').removeClass('hover');
$('.button' + counter).addClass('hover');
counter++;
}, 4000);
}
JSFiddle
Try this
var divs = $('#buttonblock').children('div'),
number = divs.length,
currentIndex = 0,
intervalLength = 2000;
function setTimer() {
divs.removeClass('hover');
divs.eq(currentIndex).addClass('hover');
currentIndex++;
if (currentIndex == number) {
currentIndex = 0;
}
}
setTimer();
var timer = setInterval(setTimer, intervalLength);
divs.mouseenter(function () {
clearInterval(timer);
divs.removeClass('hover');
var div = $(this);
div.addClass('hover');
currentIndex = divs.index(div);
}).mouseleave(function () {
timer = setInterval(setTimer, intervalLength);
});
Example - setInterval
or using setTimeout

Categories

Resources