Core Coding®

Detect Scrollbar Widths

  Detect Scrollbar Widths
JavaScript for IE and FF to detect a users scrollbar width in pixels for advanced webpage development.
<?php
function getScrollbarWidth() {
var
sBarWidth = 0;
var
scr = null;
var
inn = null;

if (
is_ie) {
// create form
scr = document.createElement('form');

// move form off screen so no one can see it
scr.style.position = 'absolute';
scr.style.top = '-1000px';
scr.style.left = '-1000px';

// create a text area
inn = document.createElement('textarea');

//set id so we can grab it later
inn.setAttribute('id', 'ta');

// add textarea to form
scr.appendChild(inn);

// add the element to the document
document.getElementsByTagName("body")[0].appendChild(scr);

// grab the text area by id
var tarea = fetch_object('ta');

// turn scroll bars off
tarea.wrap = 'off';

// get height
sBarWidth = tarea.offsetHeight;

// turn scroll bars on
tarea.wrap = 'soft';

// get difference
sBarWidth -= tarea.offsetHeight;
} else {
var
wNoScroll = 0;
var
wScroll = 0;

// Outer scrolling div
scr = document.createElement('div');

// move form off screen so no one can see it
scr.style.position = 'absolute';
scr.style.top = '-1000px';
scr.style.left = '-1000px';

// set binding height and width
scr.style.width = '100px';
scr.style.height = '50px';

// Start with no scrollbar
scr.style.overflow = 'hidden';

// Inner content div
inn = document.createElement('div');
inn.style.width = '100%';
inn.style.height = '200px';

// Put the inner div in the scrolling div
scr.appendChild(inn);

// Append the scrolling div to the doc
document.body.appendChild(scr);

// Width of the inner div sans scrollbar
wNoScroll = inn.offsetWidth;

// Add the scrollbar
scr.style.overflow = 'auto';

// Width of the inner div width scrollbar
wScroll = inn.offsetWidth;

// Pixel width of the scrolbar
sBarWidth = (wNoScroll - wScroll);
}

// Remove the scrolling div from the doc
document.body.removeChild(document.body.lastChild);

return
sBarWidth;
}

Go back to resources
Home Mail GitHub