<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:
-
Give the element an
id
in the<body>
of your code using:
id="exampleId"
-
Change the position mode in the
<style>
block:
position: absolute;
-
Use Javascript to assign new top and left positions in the
<script>
block:
document.querySelector( "#exampleId" ).style.top = 100 + "px";
document.querySelector( "#exampleId" ).style.left = 50 + "px";
Common problems
- Nothing will move until you change the positioning mode
-
The spelling and capitalization of the
id
s must be exactly the same. For example, exampleId is not the same as exampleID. -
The top and left positions must be a string that includes
"px"
.
Works:document.querySelector( "#exampleId" ).style.left = 50 + "px";
Broken:document.querySelector( "#exampleId" ).style.left = 50;
Broken:document.querySelector( "#exampleId" ).style.left = 50px;
Learn more
- w3schools.com on top style and left style
Code example
...is made with the following code:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
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 - 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
-->
<style>
/* NOTHING will happen unless you change the position mode */
#imgId {
position: absolute;
width: 100px;
}
</style>
</head>
<body>
<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>
<button id="leftButtonId">
Move to 200 pixels from the left
</button>
<br>
<img
id="imgId"
alt="Yum! Sushi!"
src="https://www.kasandbox.org/programming-images/food/sushi.png">
<script>
//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;
</script>
</body>
</html>