Chapter 12 - Function Junction - Start

The starting point for the project from Lesson 12 of JavaScript for Kids For Dummies by Chris Minnick and Eva Holland

by Phoebe Jeske

HTML

<div id="container">
    <p>
        <ul>
            <!-- instructions go here -->
        </ul>
    </p>
    <div id="track">
        <div id="train"><img src="https://www.watzthis.com/images/train.png"></div>
    </div>
    <div id="stopButton">Stop!</div>
</div>

CSS

body {
    font-family: Arial,sans-serif;
}
#container {
    padding: 10px;
    width: 360px;
    height: 80%;
    background-color: #00FF00;
}
#track {
    width: 400px;
    border-top: 10px solid white;
    border-bottom: 10px solid white;
    margin: 0px auto;
}
#train {
    height: 92px;
    width: 100px;
    position: relative;
    left: 0px;
}
#stopButton {
    padding-top: 30px;
    margin: 30px auto;
    background-color: white;
    width: 300px;
    height: 150px;
    color: brown;
    text-align:left;
    font-size: 30px;
    line-height: 50px;
}

JavaScript

/*
create three global variables:
* trainSpeed (initial value = 250)
* trainPosition (initial value = 0)
* animation (no initial value)
*/
var trainSpeed = 250;
var trainPosition = 0;
var animation;
/*
listen for click events on the train element and call a function named speedUp when they happen. 
*/
var train = document.getElementById("train");
train.addEventListener("click",speedUp);
/*
listen for click events on the stop button element and call a function called stopTrain when they happen. 
*/
var stopButton = document.getElementById("stopButton");
stopButton.addEventListener("click",stopTrain);
function speedUp() {
if(trainSpeed > 10) {
trainSpeed -= 10
clearInterval(animation);
animation = setInterval(frame, trainSpeed);
}
    /* 
   check whether the train is already going as fast as it can. If not, increase the speed.
    */
    
    /*
    If the train is already moving, stop it and then restart with the new speed by calling a function called frame.
    */


    function frame() {
       trainPosition += 2;
       train.style.left = trainPosition + 'px';
       checkPosition(trainPosition);/* 
        reposition the train and check whether the train is crashed
        */
    }
}

function checkPosition(currentPosition) {
    if(currentPosition === 260) {
    alert("Crash!");
    console.log("Crash!");
    clearInterval(animation);/*
  check the train's current position and crash it if it's at the end of the line
    */
}

function stopTrain() {
    if(trainPosition < 260) {
    clearInterval(animation);/* 
   test whether the train is already crashed. If not, stop the train. 
    */
}