JSFiddle - React, Tailwind, and code Playground
by GolfGirl21
HTML
<div id="container">
<p>
<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>
</p>
<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: green;
}
#track {
width: 492px;
border-right: 20px solid purple;
border-bottom: 2px solid blue;
margin: 20px auto;
}
#train {
height: 92px;
width: 100px;
position: relative;
left: 0px;
}
#stopButton {
padding-top: 15px;
margin: 10px auto;
background-color: red;
width: 100px;
height: 50px;
color: magenta;
text-align:center;
font-size: 24px;
line-height: 30px;
}
#stopButton:hover {
background: red;
}
JavaScript
var delayBetweenFrames = 250, trainPosition = 0, animationInterval, train, 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!");
}
}
function stopTrain() {
clearInterval(animationInterval);
if (trainPosition >= 250) {
console.log("Whew! That was close!");
alert("Whew! That was close!");
}
}