//OUTPUT: Changing an element's position

<New code>

//OUTPUT: document.querySelector( "#exampleId" ).style.top = 100 + 'px';
— positions #exampleId 100 pixels from the top
//OUTPUT: document.querySelector( "#exampleId" ).style.left = 200 + 'px';
— 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">

            OUTPUT - Changing an element's position
            content="Learn how to change positions of elements in Javascript">
        <meta name="author" content="Dave Drapak">
            Change log:
                26. Sept 2015   - created                                       - Drapak
                2. Oct          - simplified code and added console logs        - Drapak
                5. March 2017   - reworked for clearer programming style        - Drapak
                9. October 2018 - updated id style and clarified                - Drapak
            /* NOTHING will happen unless you change the position mode */
            #imgId {
                position:   absolute;
                width:      100px;
        <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
            alt="Yum! Sushi!"

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

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