Posted By

alberomo on 07/30/11


Tagged

manual functionmoveElementanimationjs


Versions (?)

moveElement Function


 / Published in: JavaScript
 

Description: JS function that moves an element. Arguments: ID of the element to move, final x point, final y point, interval/speed (in milliseconds).

From book Dom Scripting by Jeremy Keith.

  1. function moveElement(elementID,final_x,final_y,interval) {
  2. if (!document.getElementById) return false;
  3. if (!document.getElementById(elementID)) return false;
  4. var elem = document.getElementById(elementID);
  5. var xpos = parseInt(elem.style.left);
  6. var ypos = parseInt(elem.style.top);
  7. if (xpos == final_x && ypos == final_y) {
  8. return true;
  9. }
  10. if (xpos < final_x) {
  11. xpos++;
  12. }
  13. if (xpos > final_x) {
  14. xpos--;
  15. }
  16. if (ypos < final_y) {
  17. ypos++;
  18. }
  19. if (ypos > final_y) {
  20. ypos--;
  21. }
  22. elem.style.left = xpos + "px";
  23. elem.style.top = ypos + "px";
  24. var repeat = "moveElement('"+elementID+"',"+final_x+","+final_y+","+interval+")";
  25. movement = setTimeout(repeat,interval);
  26. }

Report this snippet  

You need to login to post a comment.