//OUTPUT: Changing an element's position

<New code>

//OUTPUT: document.getElementById("exampleID").style.top = 100px;
— positions #exampleID 100 pixels from the top
//OUTPUT: document.getElementById("exampleID").style.left = 200px;
— positions #exampleID 200 pixels from the top

You can move things around easily

You can make Javascript programs move things from their initial positions. It is a three part process:

Common problems

Learn more

Code example

...is made with the following code:

<!doctype html>
<html lang="en">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>drapak.ca - Computer Programming 12: OUTPUT - Changing an element's position</title>
        <meta name="description" content="Learn how to change positions of elements in Javascript">
        <meta name="author" content="Dave Drapak">
            Change log:
                26. Sept 2015   - created
                2. Oct          - simplified code and added console logs
                5. March 2017   - reworked for clearer programming style
            /* nothing will happen unless you change the position mode */
            #imgID {
                width: 100px;
                position: absolute;
        <h1>Changing the position of an element</h1>
        <p>First, make sure that you change the <code>position</code> mode.</p>

        <button id="topButtonID">
            Move to 50 pixels from the top
        <button id="leftButtonID">
            Move to 200 pixels from the left

            //OUTPUT: move image to 100 pixels from the TOP:
            var changeTopPosition = function () {
                console.log('in changeTopPosition...');
                document.getElementById('imgID').style.top  = "50px";

            //OUTPUT: move image to 200 pixels from the LEFT:
            var changeLeftPosition = function () {
                console.log('in changeLeftPosition...');
                document.getElementById('imgID').style.left = "200px";
            //INPUT: trigger changeTopPosition when #topButtonID is clicked
            document.getElementById('topButtonID').onclick  = changeTopPosition;
            //INPUT: trigger changeLeftPosition when #leftButtonID is clicked
            document.getElementById('leftButtonID').onclick = changeLeftPosition;