Posted By

martin_rusev on 05/19/10


Tagged

size scrollbar


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

keidash


Scrollbar Size


 / Published in: JavaScript
 

Wrapped in an anonymous call-once function, and the scrollbar width/height is assigned to the window object so you can reuse it everywhere without calling the function more than once.

  1. (function()
  2. {
  3.  
  4. /*
  5. This function calculates window.scrollbarWidth and window.scrollbarHeight
  6.  
  7. This must be called
  8. “onload” to work correctly (or on “DOM ready”, if you’re using
  9. a framework that provides such an event)
  10. */
  11.  
  12. var i = document.createElement('p');
  13. i.style.width = '100%';
  14.  
  15. i.style.height = '200px';
  16.  
  17. var o = document.createElement('div');
  18. o.style.position = 'absolute';
  19. o.style.top = '0px';
  20. o.style.left = '0px';
  21. o.style.visibility = 'hidden';
  22. o.style.width = '200px';
  23. o.style.height = '150px';
  24. o.style.overflow = 'hidden';
  25. o.appendChild(i);
  26.  
  27. document.body.appendChild(o);
  28. var w1 = i.offsetWidth;
  29. var
  30. h1 = i.offsetHeight;
  31. o.style.overflow = 'scroll';
  32. var w2 = i.offsetWidth;
  33. var h2 = i.offsetHeight;
  34. if (w1 == w2) w2 = o.clientWidth;
  35. if (h1 == h2) h2 = o.clientWidth;
  36.  
  37. document.body.removeChild(o);
  38.  
  39. window.scrollbarWidth = w1-w2;
  40. window.scrollbarHeight = h1-h2;
  41.  
  42. })();

Report this snippet  

You need to login to post a comment.