//MAKE: 2.05 Skill-builder: Move things with buttons


Saving your work

Use Save as... to save the empty template as "2.05S-MoveThingsWithButtons-LastName.html" in your Computer Programming 12 directory.

The assignment

Reuse, copy, and modify the code below to create a page that uses Javascript to move an image up, down, left, and right.

For example

The following is used to move an image of a star down 15px with each press of the button:

image of a star

Distance to move for each button press: px

Show me the code!

<!doctype html>
<html lang="en">
        <meta charset="UTF-8">
        <title>drapak.ca - Move things with buttons</title>
        <meta name="description" content="Assignment: Use Javascript to read current positions and move to a new one.">
        <meta name="author" content="Dave Drapak">
            Change log:
                29. Sept 2015   - created!
                5. March 2017   - reworked for clearer style

            #imageID {
                position:   absolute;
                top:        50px;   
                left:       300px;
            input {
                width:      50px;

            alt="image of a star"
            Distance to move for each button press:
            <input id="distanceID" type="text" value="15">px
            <button id="buttonID">&darr;</button>
                A reference for arrow symbols:
                up = &uarr;     down =&darr;    left = &larr;   right = &rarr;

            // This reads the distance per click and moves the star down by that amount
            var moveDown = function () {
                console.log('in moveDown...');
                // INPUT: get the distance to move with each click
                // .value returns a string - you convert it to a number with parseInt()
                var distancePerClick    = parseInt( document.getElementById('distanceID').value );
                // INPUT: get the image's current distance from the top of the page
                var currentTop          = document.getElementById('imageID').offsetTop;
                // PROCESS: increase the distance from the top by the distance per click
                var newTop              = currentTop + distancePerClick;
                console.log('currentTop, newTop:' + currentTop + ', ' + newTop);
                // OUTPUT: update the image with a new top value
                // note that you have to add px to the end of the number 
                document.getElementById('imageID').style.top    = newTop + 'px';
            //INPUT: trigger moveDown when #buttonID is clicked
            document.getElementById('buttonID').onclick = moveDown;