Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YUI - Get True element width?

Tags:

width

yui

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;
}
like image 200
JasonS Avatar asked Oct 26 '22 03:10

JasonS


1 Answers

There is an offsetWidth property that returns exactly what you want.

like image 156
casablanca Avatar answered Nov 08 '22 14:11

casablanca