faqts : Computers : Programming : Languages : JavaScript : Images

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

27 of 49 people (55%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I move an image using javascript? I can't get the "Simple animated layers" version to work.

Mar 24th, 2003 10:32
Klaus Bolwin, The N00bifier,


The following code works in MSIE and Mozilla and can move an image
horizontally, however it shouldn't be a problem to complete the code for
two dimensional moves:
var startpos, diffpos=0;
var erlaubt = false;
function Position(Ereignis)
{
if (!document.all)
   startpos = Ereignis.screenX + diffpos;
else
   startpos = event.clientX + diffpos;
erlaubt = true;
return false;
}
function Aktion(Ereignis)
{
erlaubt = false;
return false;
}
function NeuPos(Ereignis)
{
if (erlaubt)
   {
      if (!document.all)
         jetztpos = Ereignis.screenX;
      else
         jetztpos = event.clientX;
      diffpos = startpos-jetztpos;
      diffpos = Math.min(Math.max(diffpos,0),(breite3-breite2));
      document.images[1].style.left = -diffpos + "px";
   }
}
document.onmousedown = Position;
document.onmouseup = Aktion;
document.onmousemove = NeuPos;
This code is a section of a script which moves an image in a div. The
image is cliped horizontally by the style rule overflow:hidden; 
To ensure, that the div is always completely filled with the immage, 
the variable diffpos is restricted to resonable values by the
Math.min, Math.max directives.
You can move the image by drag n' drop, clicking anywhere in the window.