JSFiddle - React, Tailwind, and code Playground
by rbrousla
HTML
<div id="container">
<ul>
<li>Click the train to make it go faster.</li>
<li>Click the Stop button to stop the train.</li>
<li>Try to stop it as close to the wall as you can, without crashing.</li>
</ul>
<div id="track">
<div id="train">
<img src="http://tinyurl.com/oord7es">
</div>
</div>
<div id="stopButton">Stop!</div>
</div>
CSS
body {
font-family: Arial, sans-serif;
}
#container {
padding: 10px;
width: 540px;
height: 80%;
background-color: yellow;
}
#track {
width: 492px;
border-right: 20px solid red;
border-bottom: 2px solid grey;
margin: 20px auto;
}
#train {
height: 92px;
width: 100px;
position: relative;
left: 0px;
}
#stopButton {
padding-top: 15px;
margin: 10px auto;
background-color: gray;
width: 100px;
height: 50px;
color: yellow;
text-align:center;
font-size: 24px;
line-height: 30px;
}
#stopButton:hover {
background: red;
}
JavaScript
var delayBetweenFrames = 250;
var trainPosition = 0;
var animationInterval;
var train;
var stopButton;
train = document.getElementById("train");
train.addEventListener("click", speedUp);
stopButton = document.getElementById("stopButton");
stopButton.addEventListener("click", stopTrain);
function speedUp() {
if (delayBetweenFrames > 10) {
delayBetweenFrames -= 10;
}
console.log("Delay between frames: " + delayBetweenFrames + " milliseconds");
clearInterval(animationInterval);
animationInterval = setInterval(frame, delayBetweenFrames);
function frame() {
trainPosition += 2;
train.style.left = trainPosition + 'px';
console.log("Train is at: " + trainPosition);
checkPosition(trainPosition);
}
}
function checkPosition(currentPosition) {
if (currentPosition === 260) {
clearInterval(animationInterval);
alert("You crashed!");
console.log("Crash!");
train.addEventListener("click", goNoFurther);
}
}
function stopTrain() {
clearInterval(animationInterval);
if (trainPosition > 250 && trainPosition <= 259) {
console.log("Whew! That was close!");
alert("Whew! That was close!");
}
}
function goNoFurther() {
clearInterval(animationInterval);
console.log("Train can't move any further!");
alert("Train can't move any further!");
}