Wait for a timer to complete before seeing the result - javascript

I want to get the timer first, then see the result. When I open the page, and start the function war() it shows the result, then it shows the cooldown in the set color. I want to get the cooldown first, then the result.
JavaScript:
var points = 100;
function war() {
var dealer = document.getElementById("dealer");
var player = document.getElementById("player");
var winner = document.getElementById("winner");
var winner1 = document.getElementById("winner");
var screen = document.getElementById("points");
var dealercard = Math.floor(Math.random() * 10) + 1;
var playercard = Math.floor(Math.random() * 10) + 1;
dealer.innerHTML = dealercard;
player.innerHTML = playercard;
var skaiciuoklis = 5;
var naujaselemnt = document.createElement("p");
naujaselemnt.innerHTML = "Wait... 5 seconds.";
var idwar;
dealer.parentNode.replaceChild(naujaselemnt, dealer);
idwar = setInterval(function() {
skaiciuoklis--;
if (skaiciuoklis < 0) {
winner1.parentNode.replaceChild(dealer, naujaselemnt);
clearInterval(idwar);
} else {
winner1.innerHTML = "Wait... " + skaiciuoklis.toString() + " seconds.";
}
}, 500);
if (dealercard > playercard) {
winner.style.color = "red";
winner.innerHTML = "You lost 20 points";
} else {
winner.style.color = "green";
winner.innerHTML = "You won 10 points!";
}
if (dealercard == playercard) {
winner.style.color = "blue";
winner.innerHTML = "WAR. You won 20 points!"
}
if (dealercard < playercard) {
points = points + 10;
screen.innerHTML = points;
}
if (dealercard == playercard) {
points = points + 20;
screen.innerHTML = points;
}
if (dealercard > playercard) {
points = points - 20;
screen.innerHTML = points;
}
if (points <= 0) {
winner.style.color = "red";
winner.innerHTML = "Game Over";
alert("Game Over. REFRESH PAGE TO RETRY!");
points = 100;
}

You can use ES6 async await and move your timer to a separate function outside. You have a lot of variables and it isn't so clear but it looks like your timer is in the function war(). Javascript is asynchronous and it will move to next code even if you have a timer.
An example like this:
function timer(){
// implement timer
}
async function war() {
// at the line u want to call the timer
await timer();
}

Related

Why the button is not working when function is used in another function in javascript?

I am learning DOM from udemy and stuck here without any hint that why when I am formatting my code and trying to use a function in event listener function value then it stops working.
This is the original Code
let secretNumber = Math.round(Math.random() * 99) + 1;
let score = 20;
let highscore = 0;
document.querySelector(".check").addEventListener("click", function () {
const guess = Number(document.querySelector(".guess").value);
//Main Function used for DOM queryselection
const displayFunct = function (className, message) {
document.querySelector(className).textContent = message;
};
//When there is no input
if (!guess) {
displayFunct(".message", "No Value๐Ÿฎ๐Ÿฎ๐Ÿฎ๐Ÿฎ๐Ÿฎ");
}
//When player Wins
else if (guess === secretNumber) {
displayFunct(".message", "Correct Number ๐Ÿ˜Ž๐Ÿ˜Ž๐Ÿ˜Ž");
document.querySelector("body").style.backgroundColor = "#60b347";
document.querySelector(".number").style.width = "30rem";
if (score > highscore) {
highscore = score;
}
displayFunct(".highscore", highscore);
}
// When guess is wrong
else if (guess !== secretNumber) {
if (score > 1) {
displayFunct(".message", guess > secretNumber ? "Too HIGH" : " Too LOW");
score--;
displayFunct(".score", score);
} else {
displayFunct(".message", "You Lose!!!!");
displayFunct(".score", 0);
}
}
});
//Coding Challenge 1
document.querySelector(".again").addEventListener("click", function () {
secretNumber = Math.round(Math.random() * 99) + 1;
score = 20;
//Messages Default
document.querySelector(".number").textContent = "?";
document.querySelector(".message").textContent = "Start guessing...";
document.querySelector(".score").textContent = score;
document.querySelector(".guess").value = "";
//CSS Default
document.querySelector("body").style.backgroundColor = "#222";
document.querySelector(".number").style.width = "15rem";
});
In the Coding Challenge 1 section under Message default whenever I am using DisplayFunc()
instead of first 3 code lines then again button stops resetting my code.
This is how I want it to be but It is not happening.
//Coding Challenge 1
document.querySelector(".again").addEventListener("click", function () {
secretNumber = Math.round(Math.random() * 99) + 1;
score = 20;
//Messages Default
DisplayFunc("number", "?" )
DisplayFunc(".message", "Start guessing..." )
DisplayFunc(".score",score)
document.querySelector(".guess").value = "";
//CSS Default
document.querySelector("body").style.backgroundColor = "#222";
document.querySelector(".number").style.width = "15rem";
});
The problem is the location of your displayFunct.
You defined it inside document.querySelector(".check").addEventListener("click", function () { but you are trying to use it inside another function document.querySelector(".again").addEventListener("click", function () {.
That will never work.Move it outside the first function and both functions will be able to use it.
In the second function you are calling DisplayFunc instead of displayFunct, so that's also wrong.
let secretNumber = Math.round(Math.random() * 99) + 1;
let score = 20;
let highscore = 0;
//Main Function used for DOM queryselection
const displayFunct = function (className, message) {
document.querySelector(className).textContent = message;
};
document.querySelector(".check").addEventListener("click", function () {
...

Javascript high score update regardless of whether new score is higher or not

Newbie here! Apologies if I have not formatted this correctly.
I have a whack-a-mole game and want to keep score in local storage. The function at the bottom called 'highscore' is not working - it updates the 'highscore' regardless of whether it is in fact higher than the previous score or not!
I'm sure I'm missing something super obvious, like I say, very new to this! Only using Vanilla Javascript at this stage so hints or solutions in keeping would be ideal.
Any help or pointers in the right direction much appreciated!
Thank you!
window.onload = function() {
setUp();
count = 0;
myDiv = document.getElementById("mole");
myDiv.addEventListener("click", function() {});
};
function setUp() {
let img = document.createElement("img");
img.src = "mole.png";
img.onclick = function(event) {
whackedMole();
};
img.className = "mole";
img.id = "mole";
document.getElementById("moleMap")
.rows[randomNumber()].cells[randomNumber()].appendChild(img);
}
function randomNumber() {
return Math.floor(Math.random() * 5);
}
function whackedMole() {
let mole = document.getElementById("mole");
let audio = new Audio('whack-audio.wav');
audio.play();
document.getElementById("counter").innerHTML = (++count);
mole.parentNode.removeChild(mole);
setUp();
}
let myTimer = 0;
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 10;
function myClock() {
document.getElementById("countdown").innerHTML = --c;
if (c <= 0) {
clearInterval(myTimer);
alert("Your score is " + count + "!");
highscore();
document.getElementById("counter").innerHTML = 0;
count = 0;
}
}
}
//This is the function in question;
function highscore() {
document.getElementById("highscore").innerHTML = count;
let highscore = count;
if (count <= highscore) {
return;
} else if (count > highscore) {
localStorage.setItem('highscore', count);
}
}
If i understood correctly the problem lies in this code:
function highscore() {
document.getElementById("highscore").innerHTML = count;
let highscore = count;
if (count <= highscore) {
return;
} else if (count > highscore) {
localStorage.setItem('highscore', count);
}
}
and specifically on these two lines:
document.getElementById("highscore").innerHTML = count;
and
let highscore = count;
Everytime you call highscore(); you are updating your DOM regardless of if the count is > than the highscore. Then on the second line of code that i have hinted highscore gets the value of count so the first statement in the if clause will always evaluate to true. What i would do is modify the code as following:
function highscore() {
// Just in case the highscore is not yet initialized.
if (!localstorage.getItem('highscore')) {
localstorage.setItem('highscore', count);
}
let highscore = localstorage.getItem('highscore');
if (count <= highscore) {
return;
} else if (count > highscore) {
document.getElementById("highscore").innerHTML = count;
localStorage.setItem('highscore', count);
}
}

Cannot get content of div to store locally and load locally

I have a JS function to save and load content of a notepad I've made, locally.
I tried to replicate this for a div which contains times of a stopwatch.(see code below)
The stopwatch when paused will write it's time to this div to be saved, I want these times to save when I refresh / close and reopen the page.
It works for my notes in the notepad, please can someone explain where I'm going wrong?
JavaScript for save function:
//Storage of Text-Box
const notesInput = document.querySelector('#notes');
function remFunc() {
// store the entered name in web storage
localStorage.setItem('notes', notes.value);
}
function loadfunc() {
if(localStorage.getItem('notes')) {
let notes_var = localStorage.getItem('notes');
notes.value= notes_var;
} else {
}
}
document.body.onload = loadfunc();
//Storage of Times DIV
const output = document.querySelector('#output');
function remfunc2() {
localStorage.setItem('output', outContent.innerHTML);
}
function loadfunc2() {
if(localStorage.getItem('output')) {
let output_var = localStorage.getItem('output');
output.innerHTML = output_var ;
} else {
}
}
document.body.onload = loadfunc2();
This is the div:
<div id="output" name="output" class="buttonZ logPad"></div>
Here is the stopwatch Javascript:
// Timer JS
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
function startstop()
{
var startstop = document.getElementById('startstopbutton');
var startdate = new Date();
var starttime = startdate.getTime();
if(flagclock==0)
{
startstop.value = 'Stop';
flagclock = 1;
counter(starttime);
}
else
{
startstop.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
logTime();
}
}
function counter(starttime)
{
output = document.getElementById('output');
clock = document.getElementById('clock');
currenttime = new Date();
var timediff = currenttime.getTime() - starttime;
if(flagstop == 1)
{
timediff = timediff + stoptime
}
if(flagclock == 1)
{
clock.innerHTML = formattime(timediff,'');
clock.setAttribute('value', formattime(timediff, ''));
refresh = setTimeout('counter(' + starttime + ');',10);
}
else
{
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function formattime(rawtime,roundtype)
{
if(roundtype == 'round')
{
var ds = Math.round(rawtime/100) + '';
}
else
{
var ds = Math.floor(rawtime/100) + '';
}
var sec = Math.floor(rawtime/1000);
var min = Math.floor(rawtime/60000);
ds = ds.charAt(ds.length - 1);
if(min >= 60)
{
startstop();
}
sec = sec - 60 * min + '';
if(sec.charAt(sec.length - 2) != '')
{
sec = sec.charAt(sec.length - 2) + sec.charAt(sec.length - 1);
}
else
{
sec = 0 + sec.charAt(sec.length - 1);
}
min = min + '';
if(min.charAt(min.length - 2) != '')
{
min = min.charAt(min.length - 2)+min.charAt(min.length - 1);
}
else
{
min = 0 + min.charAt(min.length - 1);
}
return min + ':' + sec + ':' + ds;
}
function resetclock()
{
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
if(flagclock !== 0) {
startstopbutton.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
}
if(flagclock == 1)
{
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
}
else
{
clock.innerHTML = "00:00:0";
}
}
//Split function
function splittime()
{
if(flagclock == 1)
{
if(splitdate != '')
{
var splitold = splitdate.split(':');
var splitnow = clock.innerHTML.split(':');
var numbers = new Array();
var i = 0
for(i;i<splitold.length;i++)
{
numbers[i] = new Array();
numbers[i][0] = splitold[i]*1;
numbers[i][1] = splitnow[i]*1;
}
if(numbers[1][1] < numbers[1][0])
{
numbers[1][1] += 60;
numbers[0][1] -= 1;
}
if(numbers[2][1] < numbers[2][0])
{
numbers[2][1] += 10;
numbers[1][1] -= 1;
}
}
splitdate = clock.innerHTML;
output.innerHTML += (++splitcounter) + '. ' + clock.innerHTML + '\n';
}
}
function logTime() {
const time = document.getElementById('clock').getAttribute('value');
document.getElementById('output').innerHTML += (++splitcounter) + '. ' + time + '<br />';
}
function time() {
splittime();
resetclock();
}
Any help will be much appreciated! Thank you.
Okay, so I figured out what I was doing wrong.
The 'output' variable was being used in the timer code.
This prevented me from setting the variable correctly.
I changed the id for the div and the variable name i was using.
I ran this code in my console on this page and it is working:
let counter = 0;
const outContent = document.querySelector('#notify-container');
setInterval(function()
{
counter++;
outContent.innerHTML = `${counter*2} seconds`;
localStorage.setItem('output', outContent.innerHTML);
}, 2000);
function loadfunc2() {
if(localStorage.getItem('output')) {
let output_var = localStorage.getItem('output');
outContent.innerHTML = output_var ;
counter = parseInt(outContent.innerHTML.split(' ')[0], 10)
}
}
loadfunc2()
Paste it into the console, run it, leave it for a few seconds, then refresh the page, paste it and run it again. You can see it working.

How do I get my timer to stop, when my 10th and last question has been answered?

The goal I am trying to achieve is to get my timer to stop when all the questions of my quiz has been answered. I have 10 total questions. I have been able to get the timer to start. But getting ot to stop on the click of submit on the 10th question is something I can't figure out.
Let me know if you know what I am doing
StackOverflow said my code was too long... I added my code to codepen. I also included my JS on here.
// variables
var score = 0; //set score to 0
var total = 10; //total nmumber of questions
var point = 1; //points per correct answer
var highest = total * point;
//init
console.log('script js loaded')
function init() {
//set correct answers
sessionStorage.setItem('a1', "b");
sessionStorage.setItem('a2', "a");
sessionStorage.setItem('a3', "c");
sessionStorage.setItem('a4', "d");
sessionStorage.setItem('a5', "b");
sessionStorage.setItem('a6', "d");
sessionStorage.setItem('a7', "b");
sessionStorage.setItem('a8', "b");
sessionStorage.setItem('a9', "d");
sessionStorage.setItem('a10', "d");
}
// timer
// var i = 1;
// $("#startButton").click(function (e) {
// setInterval(function () {
// $("#stopWatch").html(i);
// i++;
// }, 1000);
// });
// $("#resetButton").click(function (e) {
// i = 0;
// });
//hide all questions to start
$(document).ready(function() {
$('.questionForm').hide();
//show question 1
$('#question1').show();
$('.questionForm #submit').click(function() {
//get data attribute
current = $(this).parents('form:first').data('question');
next = $(this).parents('form:first').data('question') + 1;
//hide all questions
$('.questionForm').hide();
//show next question in a cool way
$('#question' + next + '').fadeIn(400);
process('' + current + '');
return false;
});
});
//process answer function
function process(n) {
// get input value
var submitted = $('input[name=question' + n + ']:checked').val();
if (submitted == sessionStorage.getItem('a' + n + '')) {
score++;
}
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3> <button onclick="myScore()">Add Your Name To Scoreboard!</a>')
}
return false;
}
window.yourPoints = function() {
return n;
}
function myScore() {
var person = prompt("Please enter your name", "My First Name");
if (person != null) {
document.getElementById("myScore").innerHTML =
person + " " + score
}
}
// function showTime() {
// var d = new Date();
// document.getElementById("clock").innerHTML = d.toLocaleTimeString();
// }
// setInterval(showTime, 1000);
var x;
var startstop = 0;
window.onload = function startStop() { /* Toggle StartStop */
startstop = startstop + 1;
if (startstop === 1) {
start();
document.getElementById("start").innerHTML = "Stop";
} else if (startstop === 2) {
document.getElementById("start").innerHTML = "Start";
startstop = 0;
stop();
}
}
function start() {
x = setInterval(timer, 10);
} /* Start */
function stop() {
clearInterval(x);
} /* Stop */
var milisec = 0;
var sec = 0; /* holds incrementing value */
var min = 0;
var hour = 0;
/* Contains and outputs returned value of function checkTime */
var miliSecOut = 0;
var secOut = 0;
var minOut = 0;
var hourOut = 0;
/* Output variable End */
function timer() {
/* Main Timer */
miliSecOut = checkTime(milisec);
secOut = checkTime(sec);
minOut = checkTime(min);
hourOut = checkTime(hour);
milisec = ++milisec;
if (milisec === 100) {
milisec = 0;
sec = ++sec;
}
if (sec == 60) {
min = ++min;
sec = 0;
}
if (min == 60) {
min = 0;
hour = ++hour;
}
document.getElementById("milisec").innerHTML = miliSecOut;
document.getElementById("sec").innerHTML = secOut;
document.getElementById("min").innerHTML = minOut;
document.getElementById("hour").innerHTML = hourOut;
}
/* Adds 0 when value is <10 */
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function reset() {
/*Reset*/
milisec = 0;
sec = 0;
min = 0
hour = 0;
document.getElementById("milisec").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("hour").innerHTML = "00";
}
//adding an event listener
window.addEventListener('load', init, false);
https://codepen.io/rob-connolly/pen/xyJgwx
Any help would be appreciated.
its a pretty simple solution just call the stop function in the if condition of n == total
if (n == total) {
$('#results').html('<h3>Your score is: ' + score + ' out of ' + highest + '!</h3>
<button onclick="myScore()">Add Your Name To Scoreboard!</a>')
stop()
}
https://codepen.io/nony14/pen/VwYREgr
Try using clearInterval() to stop the timer.
https://codepen.io/thingevery/pen/dyPrgwz

How to Change 2 Math.floor random numbers if they are equal

I'm trying to replicate the Monty Hall Problem, if you've heard of it, and I need to add in a system that will change one of two Math.floor random numbers when they are equal. My question is how do I change a variable that is random into another if it is equal to a second random variable. If you look into the Monty Hall Problem, the wrong variable would be an incorrect choice and door is correct, I set both to be random, but obviously, they cannot both be equal. This is what I have so far.
setInterval(gr, 1000)
function gr() {
if (wrong === door) {
door = Math.floor((Math.random() * 3) + 1);
}
}
var door1 = 0;
var door2 = 0;
var door3 = 0;
var door;
var wrong;
var attempt = 0;
var d1 = document.getElementById('door1');
var d2 = document.getElementById('door2');
var d3 = document.getElementById('door3');
setInterval(gr, 1000)
function gr() {
if (wrong === door) {
door = Math.floor((Math.random() * 3) + 1);
}
}
function dr1() {
document.getElementById('door1').style.pointerEvents = 'none';
document.getElementById('door2').style.pointerEvents = 'none';
document.getElementById('door3').style.pointerEvents = 'none';
document.getElementById('door1').style.backgroundColor = "green";
door1 = 1;
if (door2 === 1) {
document.getElementById('door2').style.backgroundColor = "black";
door2 = 0;
} else if (door3 === 1) {
document.getElementById('door3').style.backgroundColor = "black";
door3 = 0;
}
if (attempt === 0) {
wrong = Math.floor((Math.random() * 2) + 1);
door = Math.floor((Math.random() * 3) + 1);
if (wrong === 1) {
document.getElementById('door2').style.backgroundColor = "white";
change1a();
} else if (wrong === 2) {
document.getElementById('door3').style.backgroundColor = "white";
change1b();
}
}
attempt = 1;
}
function dr2() {
document.getElementById('door1').style.pointerEvents = 'none';
document.getElementById('door3').style.pointerEvents = 'none';
document.getElementById('door2').style.backgroundColor = "green";
door2 = 1;
if (door1 === 1) {
document.getElementById('door1').style.backgroundColor = "black";
door1 = 0;
} else if (door3 === 1) {
document.getElementById('door3').style.backgroundColor = "black";
door3 = 0;
}
if (attempt === 0) {
wrong = Math.floor((Math.random() * 2) + 1);
door = Math.floor((Math.random() * 3) + 1);
if (wrong === 1) {
document.getElementById('door1').style.backgroundColor = "white";
change2a();
} else if (wrong === 2) {
document.getElementById('door3').style.backgroundColor = "white";
change2b();
}
}
attempt = 1;
}
function dr3() {
document.getElementById('door1').style.pointerEvents = 'none';
document.getElementById('door2').style.pointerEvents = 'none';
document.getElementById('door3').style.backgroundColor = "green";
door3 = 1;
if (door1 === 1) {
document.getElementById('door1').style.backgroundColor = "black";
door1 = 0;
} else if (door2 === 1) {
document.getElementById('door2').style.backgroundColor = "black";
door2 = 0;
}
if (attempt === 0) {
wrong = Math.floor((Math.random() * 2) + 1);
door = Math.floor((Math.random() * 3) + 1);
if (wrong === 1) {
document.getElementById('door1').style.backgroundColor = "white";
change3a();
} else if (wrong === 2) {
document.getElementById('door2').style.backgroundColor = "white";
change3b();
}
}
attempt = 1;
}
function change1a() {
document.getElementById('door3').style.pointerEvents = "all";
}
function change1b() {
document.getElementById('door2').style.pointerEvents = "all";
}
function change2a() {
document.getElementById('door3').style.pointerEvents = "all";
}
function change2b() {
document.getElementById('door1').style.pointerEvents = "all";
}
}
I tried adapting your code, but it looked too messy for me to understand everything you wanted to do. So, instead, I decided to create my own, just for fun. You can get some inspiration in there.
To answer your specific question, this is the way I choose the door:
var selectedDoor = 1,
correctDoor = 2,
losingDoor = getLosingDoor();
function getLosingDoor() {
var losingDoor;
do {
losingDoor = Math.floor((Math.random() * 3) + 1);
} while ([correctDoor, selectedDoor].indexOf(losingDoor) > -1);
return losingDoor;
}
Full demo
// Create a MontyHall instance in the #app div
var myMontyHall = MontyHall(document.getElementById('app'));
function MontyHall(container) {
var self = {
// Will hold DOM references
refs: null,
// Will hold the MontyHall instance's state
state: null,
/*
* Creates the doors in the DOM and in the state
*/
init: function() {
self.state = {
attempts: 0,
doorCount: 3,
correctDoor: self.getRandomInt(0, 3)
};
self.refs = {
container: container,
instructions: document.createElement('p'),
doorsWrapper: document.createElement('div'),
doors: []
};
// Reset container
self.refs.container.innerHTML = '';
// Setup a container for the doors
self.refs.doorsWrapper.className = 'doors-wrapper';
self.refs.container.appendChild(self.refs.doorsWrapper);
// Setup a container for instructions
self.say('Please select a door.');
self.refs.container.appendChild(self.refs.instructions);
// For each door
for (var i=0; i<self.state.doorCount; i++) {
// Create a div
var el = document.createElement('div');
// Give it a class
el.className = 'door';
// Add click event listener
(function(index) {
el.addEventListener('click', function(){
self.clickOnDoor(index);
});
})(i);
// Append it to the doors container
self.refs.doorsWrapper.append(el);
// Store a reference to it
self.refs.doors.push(el);
}
return self;
},
/*
* Called when a door is clicked
*/
clickOnDoor: function(index) {
self.state.selectedDoor = index;
// If this is the first attempt
if (self.state.attempts === 0) {
// Show it is selected
self.refs.doors[self.state.selectedDoor].classList.add('selected');
// Find a non selected losing door
self.state.losingDoor = self.getLosingDoor();
// Open it
self.refs.doors[self.state.losingDoor].classList.add('disabled', 'loser');
// Update instructions
self.say(
'You selected door #' + (index + 1) + '.<br>'
+ 'I opened door #' + (self.state.losingDoor + 1) + ', '
+ 'it contains a sheep.<br>'
+ 'You can now keep your choice, or change your mind.'
);
self.state.attempts++;
} else {
// For each door
self.refs.doors.forEach(function(el, i) {
// Disable it
el.classList.add('disabled');
// Show it as a winner or a loser
el.classList.add(i === self.state.correctDoor ? 'winner' : 'loser');
// Show it as selected or not
el.classList.toggle('selected', i === index);
});
// Update instructions
self.say(
(
self.state.correctDoor === index ?
'<span class="green">Congratulations, you won!</span>' :
'<span class="red">Sorry, you lost...</span>'
)
+ '<br>'
+ 'The gold was behind door #' + (self.state.correctDoor + 1) + '.<br>'
+ '<button class="restart">Play again</button>'
);
// Enable restart button
self.refs.instructions.querySelector('.restart')
.addEventListener('click', self.init);
}
},
/*
* Returns the index of a losing door, which is not selected
*/
getLosingDoor: function() {
var losingDoor;
do {
losingDoor = self.getRandomInt(0, self.state.doorCount);
} while ([
self.state.correctDoor,
self.state.selectedDoor
].indexOf(losingDoor) > -1);
return losingDoor;
},
/*
* Sets the instructions innerHTML
*/
say: function(html) {
self.refs.instructions.innerHTML = html;
},
/*
* Returns an integer between min and max
*/
getRandomInt: function(min, max) {
return Math.floor((Math.random() * (max-min)) + min);
}
};
return self.init();
}
/* I minified the CSS to avoid cluttering my answer. Full version in link below */body{font-family:Arial,Helvetica,sans-serif;text-align:center}p{margin-top:.2em}button{margin-top:.5em}.door{display:inline-block;width:3em;height:5em;border:1px solid #000;margin:.5em;background-image:url(https://image.ibb.co/c7mssS/doors.jpg);background-size:300% 100%;background-position:center;cursor:pointer;box-shadow:0 0 5px 1px #1070ff;transition:all .3s ease}.door:not(.disabled):hover{opacity:.9}.door.selected{box-shadow:0 0 5px 3px #b910ff}.door.loser{background-position:right}.door.winner{background-position:left}.door.disabled{pointer-events:none}.door.disabled:not(.selected){box-shadow:none}span{font-weight:700}.green{color:#42e25d}.red{color:#ff2f00}
<div id="app"></div>
JSFiddle demo

Categories

Resources