How to move an HTML element

March 16th, 2006 in Basic Tutorials · By Markus Weichselbaum

This article discusses the principles behind JavaScript animation.

When we say “animation” in this context, we really mean “changing the position of something”. There are other types of animation, where the object doesn’t change its position but rather what is shown at its position changes. An example for that would be an animated gif image. Alas, for the purpose of this tutorial, “animation” means, making it look as if something moves using JavaScript.

Getting a handle of things

To reference an HTML element using JavaScript, we use its object handle. A handy way of doing this is by using the document.getElementById() function.

Let’s say we have an image element on our page that we want to manipulate. Note that we specified an id attribute with the img element.

<img id="demoimage" src="demo.gif" alt="" />

In JavaScript, we can get to the object like so:

demoObj=document.getElementById('demoimage');

Now we have access to all its properties, such as src and style.

Manipulating the position of an object

To set a new position for the image, we may do something like

demoObj.style.left='100px';
demoObj.style.top='50px';

And that’s all there is to it! We’ll explain in another article how the TheBroth’s tiles are animated.

The example page

Check out this HTML page which shows an example of reading and setting the position of an object using JavaScript.

Click on “Move it” and the div will advance its position a little bit.

Share this:
  • del.icio.us
  • StumbleUpon
  • Furl
  • Netscape
  • Reddit
  • Technorati
  • YahooMyWeb

One Response to “How to move an HTML element”

misschatterbox1 Apr 07

I understand html, the brackets and only when you use the brackets, that’s a bit tricky for me. Since I’m used to typing in a and a ” at the beginning and another ” at the end of a website, before enclosing with .

The brackets got me, but I successfully managed to figure it out. Thanks!

Leave a comment