Question: Exercise: The Running Motorcycles (total 5 points) Question one (2.5 points): Start with the following webpage, which has an img of a motorcycle running, and
Exercise: The Running Motorcycles (total 5 points) Question one (2.5 points): Start with the following webpage, which has an img of a motorcycle running, and JavaScript functions that animate the motorcycle across the screen. http://www.csc.lsu.edu/~qywang/CS6210/HTMLExercise/Homework2-example.html (For all of these, you shouldn't need to touch the original code - just add code below.) Add an event listener to the start button, so that the motorcylce starts moving across the screen when its clicked. Add an event listener to the stop button, so that the motorcylce stops moving when clicked. Add an event listener to the speed button, so that the motorcylce moves faster when it's clicked. Question two (2.5 points): Can you disable the start, stop, and faster buttons at the appropriate times? (e.g. the user shouldn't be able to click "stop" if the motorcylce isn't currently moving, and the user shouldn't be able to click "start" if the cat is currently moving) Hint: you can disable a button using document.getElementById("myBtn").disabled = true;
Answer:
var movePixels = 10; var delayMs = 50; var catTimer = null; function motorCycleRunning() { var img = document.getElementsByTagName('img')[0]; var currentLeft = parseInt(img.style.left); img.style.left = (currentLeft + movePixels) + 'px'; if (currentLeft > (window.innerWidth-img.width)) { img.style.left = '0px'; } } function startRunning() { catTimer = window.setInterval(motorCycleRunning, delayMs); } // #1 function onStartClick() { startCatWalk(); } var startButton = document.getElementById('start-button'); startButton.addEventListener('click', onStartClick); // #2 function onStopClick() { window.clearInterval(catTimer); } var stopButton = document.getElementById('stop-button'); stopButton.addEventListener('click', onStopClick);
// #3 function onSpeedClick() { movePixels += 5; var speed = movePixels * (1000/50); document.getElementById('info').innerHTML = 'Current speed: ' + speed + 'px/second'; } var speedButton = document.getElementById('speed-button'); speedButton.addEventListener('click', onSpeedClick);
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
