Posted By

jatkins on 05/03/11


Tagged

css element html position positioning


Versions (?)

Position one HTML element below another


 / Published in: JavaScript
 

Released into the public domain.

  1. function getRealPosition(elmnt) { // h/t to http://www.quirksmode.org/js/findpos.html
  2. elmnt = typeof elmnt == 'object' ? elmnt : document.getElementById(elmnt);
  3. elmntLeft = elmnt.offsetLeft;
  4. elmntTop = elmnt.offsetTop;
  5. while(elmnt = elmnt.offsetParent) {
  6. elmntLeft += elmnt.offsetLeft;
  7. elmntTop += elmnt.offsetTop;
  8. }
  9. return [elmntLeft, elmntTop];
  10. }
  11.  
  12. function positionBelow(elmntAbove, elmntBelow, topDiff, leftDiff) {
  13. elmntAboveRealPosition = getRealPosition(elmntAbove);
  14. elmntBelow = typeof elmntBelow == 'object' ? elmntBelow : document.getElementById(elmntBelow);
  15. elmntBelow.style.left = elmntAboveRealPosition[0] + (leftDiff ? leftDiff : 0) + 'px';
  16. elmntBelow.style.top = elmntAboveRealPosition[1] + (topDiff ? topDiff : 0) + 'px';
  17. if(elmntBelow.style.position!='absolute')
  18. elmntBelow.style.position = 'absolute';
  19. }

Report this snippet  

You need to login to post a comment.