0

Can someone list the properties that make up offsetwidth?

Also I need to calculate the offsetwidth be retrieving all these properties through javascript and summing them up. The sum of all these properties needs to be equal to the offsetwidth.

The code needs to be compatible with IE7.

Any help would be greatly appreciated. Thanks!

1 Answer 1

2

You will need a way to determine the browser's scrollbar width

// adapted from http://davidwalsh.name/detect-scrollbar-width
function getScrollBarWidth() {
    var container = document.createElement('div');
    container.style.width = '100px';
    container.style.height = '100px';
    container.style.overflow = 'scroll';
    container.style.position = 'absolute';
    container.style.top = '-9999px';
    document.body.appendChild(container);
    var width = container.offsetWidth - container.clientWidth;
    document.body.removeChild(container);
    return width;
}

You will also need a way to determine if the element has a verical scrollbar, then you just need to add up all the widths!

function getOffsetWidth(element) {
    var hasVerticalScrollbar = element.scrollHeight > element.clientHeight &&
        !(element.style.overflow && element.style.overflow == 'hidden');

    var style = getComputedStyle(element);

    var offsetWidth = (parseFloat(style.getPropertyValue('border-left-width'))) +
        (parseFloat(style.getPropertyValue('border-right-width'))) +
        element.clientWidth +
        (hasVerticalScrollbar ? getScrollBarWidth() : 0);

    return offsetWidth;
}

Here is a polyfill for window.getComputedStyle in IE7/8 - http://snipplr.com/view/13523/

Here is a working jsbin - http://jsbin.com/iboharI/1/edit?html,css,js,console,output

Reference

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetWidth https://developer.mozilla.org/en-US/docs/Determining_the_dimensions_of_elements http://caniuse.com/getcomputedstyle

1
  • @Kavun thank you for the answer! I will test this out when I get a chance and let you know. Tks!
    – slayernoah
    Commented Nov 7, 2013 at 17:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.