I am using YUI and need to get the true width of the element. The width of an element can be determined as follows.
width + border-left + border-right + padding-left + padding-right + margin-left + margin-right.
Below is what I have come up with. It appears to be working. I was just wondering if this is the best way to go about determining this or is there there a more efficient way?
YUI().use('node', function(Y) {
    var node = Y.one('#nav');
    var nodeWidth = trueElementWidth(node);
    alert(nodeWidth);
});
function trueElementWidth(el) {
    var width = 0;
    var attributes = ['border-left', 'border-right', 'padding-left', 'padding-right', 'width', 'margin-right', 'margin-left'];
    for(var i=0; i < attributes.length; i++) {
        width = width + removePx(el.getComputedStyle(attributes[i]));
    }
    return width;
}
function removePx(el) {
    el = el.toString();
    length = el.length - 2;
    elDimension = parseInt(el.substring(0, length));
    return isNaN(elDimension) ? 0 : elDimension;
}
There is an offsetWidth property that returns exactly what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With