train stoper
The finished project from Chapter 12 of JavaScript for Kids For Dummies by Chris Minnick and Eva Holland
by Daniel Hall
HTML
<div id="container">
<h1>
train stoper
</h1>
<ul>
<li>Click the train to make it go faster.</li>
<li>Click the Stop button to stop it.</li>
<li>Try to stop the train at the stop sign or you
will not be cool anymore.</li>
</ul>
</p>
<div id="track">
<div id="train">
<img src="http://www.watzthis.com/images/train.png">
</div>
</div>
<div id="stopButton">Stop!</div>
</div>
<div id="d"><p>
stop
</p>
CSS
body {
font-family: Arial, sans-serif;
background-color: #00FF00;
}
#container {
padding: 10px;
width: 97%;
height: %;
background-color: #00FF00;
}
#track {
width: 340px;
border-top: 2px solid white;
border-bottom: 2px solid white;
margin: 20px auto;
}
#train {
height: 92px;
width: 100px;
position: relative;
left: 0px;
}
#stopButton {
padding-top: 15px;
margin: 10px auto;
background-color: white;
width: 100px;
height: 50px;
color: red;
text-align:center;
font-size: 24px;
line-height: 30px;
}
#d {
position: absolute;
left: 85%;
top: 31%;
width: 14%;
height: 20%;
background-color: red;
}
JavaScript
var trainSpeed = 250;
var trainPosition = 0;
var animation;
var train = document.getElementById("train");
train.addEventListener("click", speedUp);
var stopButton = document.getElementById("stopButton");
stopButton.addEventListener("click", stopTrain);
function speedUp() {
if (trainSpeed > 10) {
trainSpeed -= 10;
}
console.log("train speed: " + trainSpeed);
clearInterval(animation);
animation = setInterval(frame, trainSpeed);
function frame() {
trainPosition += 2;
train.style.left = trainPosition + 'px';
console.log(trainPosition);
checkPosition(trainPosition);
}
}
function checkPosition(currentPosition) {
if (currentPosition === 260) {
alert("you are not cool any more");
console.log("you win!");
clearInterval(animation);
}
}
function stopTrain() {
if (trainPosition < 260) {
clearInterval(animation);
alert("you win")
console.log("you lose I am going to rock out of chamb! boo boo boo boo boo doo");
}
}