Non so se ho capito, ma vedi se riesci ad adattare:
codice:
while (element) {
  coords.x += element.offsetLeft;
  coords.y += element.offsetTop;
  if(coords.x > MAX_X) coords.x = MIN_X;
  if(coords.y > MAX_Y) coords.y = MIN_Y;
  element = element.offsetParent;
}
Dove le variabili scritte maiuscole, vanno sostituite con i dati tuoi (costanti o variabili).