15

I have to position a popup element dynamically inside a container. I'm trying to get the border width of the container. I've found several questions like this one:

How to get border width in jQuery/javascript

My problem has been discussed but I haven't found any answers. How do you get the border width when the property is thick, thin, or medium?

There's word on the street that you can usually expect thin, medium, and thick to be 2px, 4px, and 6px respectively, but the CSS spec doesn't require that.

Has anyone run across an easy (or if not easy at least consistent) way to get the width of the border on one edge of a DOM element?

10
  • There is the word on the street about what to expect, because there is no standard defined. every browser implements it in its own way. Nov 28, 2012 at 14:25
  • 1
    Is your question specifically about thick, thin and medium? These are so rarely used I would call them an edge case that a good standard can avoid.
    – Kato
    Nov 28, 2012 at 14:29
  • 2
    It's looking like that'll be the case Kato. I've never really cared for them conceptually, but I don't like to start a plugin saying, "well, don't use dumb CSS and you won't have a problem." Well, I'd like to, but I can't. :)
    – D. Patrick
    Nov 28, 2012 at 14:31
  • Is there a reason why picking up the width of each side of the border won't work for you? jsfiddle.net/CadEX Nov 28, 2012 at 14:33
  • @Rory, yeah. This plugin lets you specify a container for your popup so that you can relatively position the container. The popup needs to compensate for the relative position based on the offset and border (and probably margin but we haven't crossed that bridge yet). Even if I could count on the border being the same on both sides of the element, in IE7, ($element.outerWidth() - $element.innerWidth()) === 0 when border-width: thick|thin|medium.
    – D. Patrick
    Nov 28, 2012 at 14:36

6 Answers 6

1

You could use the .innerWidth() and .outerWidth() to get the the width with and without the borders and subtract the second from the first one.

var someElement = $("#someId");
var outer = someElement.outerWidth();
var inner = someElement.innerWidth();

alert(outer - inner); // alerts the border width in pixels
7
  • 1
    That will give you the widths of both borders together, what if one side is thicker than the other? Nov 28, 2012 at 14:27
  • 1
    rcdmk, I did start down this path, but Rory is right . . . I need to account for the borders being different widths. That's why I specifically mentioned "on one edge" in the question. Another problem is that evidently in IE7 (I have to support IE7 unfortunately), outerWidth doesn't include border widths if the border-width property is non-numeric.
    – D. Patrick
    Nov 28, 2012 at 14:30
  • @RoryMcCrossan your point is valid but this is still helpful. It's a solution that will work for many; it depends on what the widths are going to be used for, which is not specified.
    – Kato
    Nov 28, 2012 at 14:30
  • Good catch. But the only way to get the desired measure of each border is to use the .css() method, but it falls in the problematic "non-standards-world" of he already talked about. Nov 28, 2012 at 14:32
  • 1
    @rcdmk: As far as I can tell IE returns NaN values like thick or medium. I believe OP is asking how to get the actual numeric values in those cases. This answer (though useful for other questions) does not address that, seeing that jQuery outerWidth()/innerWidth() ignore NaN values.
    – Nope
    Nov 28, 2012 at 14:37
1

usualy if you have:

<div id="container">myContainer</div>

you can get the Border-Width attribute by jQuery:

var borderWidth = $('#container').css('borderWidth');
alert(borderWidth);

or for each side by:

var left = $('#container').css('borderLeftWidth');
var right = $('#container').css('borderRightWidth');
var top = $('#container').css('borderTopWidth');
var bottom = $('#container').css('borderBottomWidth');

alert(left+" "+right+" "+top+" "+bottom);
6
  • 1
    thats not what he is looking for? Nov 28, 2012 at 14:29
  • he's looking for the border width, isn't he?
    – Munchies
    Nov 28, 2012 at 14:31
  • this is a complete answer, why downvoting? Nov 28, 2012 at 14:33
  • 1
    @Munchies: OP linked a question already answerd what this answer answered but which is not what is asked. As far as I can tell IE returns NaN values like thick or medium. OP is asking how to get the actual numeric values in those cases. This answer does not address that.
    – Nope
    Nov 28, 2012 at 14:36
  • 1
    According to the fiddle I linked in the comments in the question, Chrome/Firefox come back with 1px for thin, 3px for medium and 5px for thick. Link for convinience: jsfiddle.net/CMbPN
    – Nope
    Nov 28, 2012 at 15:34
0

I played around with this for a little longer and the only solution I was able to come up with which would kind-off sort out the issue is similar to this:

var thinBorder = 1;
var mediumBorder = 3;
var thickBorder = 5;

function getLeftBorderWidth($element) {
    var leftBorderWidth = $element.css("borderLeftWidth");
    var borderWidth = 0;


    switch (leftBorderWidth) {
    case "thin":
        borderWidth = thinBorder;
        break;
    case "medium":
        borderWidth = mediumBorder;
        break;
    case "thick":
        borderWidth = thickBorder;
        break;
    default:
        borderWidth = Math.round(parseFloat(leftBorderWidth));
        break;
    }

    return borderWidth;
}

function getRightBorderWidth($element) {
    var rightBorderWidth = $element.css("borderRightWidth");
    var borderWidth = 0;


    switch (rightBorderWidth) {
    case "thin":
        borderWidth = thinBorder;
        break;
    case "medium":
        borderWidth = mediumBorder;
        break;
    case "thick":
        borderWidth = thickBorder;
        break;
    default:
        borderWidth = Math.round(parseFloat(rightBorderWidth));
        break;
    }

    return borderWidth;
}​

DEMO

Note the Math.round() and parseFloat(). Those are there because IE9 returns 0.99px for thin instead of 1px and 4.99px for thick instead of 5px.

Edit

You mentioned in the comments that IE7 has a different size for thin, medium and thick.
They seem to be off by only .5px which will be hard to deal with, seeing you most liekly need full numbers.

My suggestion would be to either simply ignore the .5px of a difference and acknowledge the most likely unnoticable imperfections when using IE7 and lower or if you are hell-bend on dealing with it to adjust the constants by that much similar to:

var thinBorder = 1;
var mediumBorder = 3;
var thickBorder = 5;

// Will be -1 if MSIE is not detected in the version string
var IEVersion = navigator.appVersion.indexOf("MSIE");

// Check if it was found then parse the version number. Version 7 will be 17 but you can trim that off with the below.
If(IEVersion > -1){
    IEVersion = parseInt(navigator.appVersion.split("MSIE")[1]);
}

// Now you can simply check if you are in an ancient version of IE and adjsut any default values accordingly.
If(IEVersion < 7){
    thinBorder = 0.5;
    mediumBorder = 3.5;
    thickBorder = 4.5;
}

/// rest as normal

Any of the above is by no means a copy-paste solution but merely a demonstration on a few ways one could deal with this issue. You would naturally wrap all those helpers into separate functions, plug-ins or extensions.

In your final solution you might even still need to deal with float off-sets and rounding issue.

This should be able to get you started though well enough.

7
  • @D.Patrick: You can off course apply the same logic to borderTopWidth and borderBottomWidth.
    – Nope
    Nov 29, 2012 at 0:19
  • Did you notice the fiddle I made in response to your fiddle comment? In any case, the problem is IE < 8 has different sizes for thin, medium, and thick. Here's the fiddle: jsfiddle.net/tncbbthositg/VM4ha
    – D. Patrick
    Nov 29, 2012 at 14:42
  • Ugh. I always hit enter when I want a linefeed and it posts the comment. Anyhow, if you take that into consideration in your script (and preferably add something about the fact that there's not a better way to do it) then I'll accept your answer. I can't accept your answer as it is because it's not correct for IE7 as far as I can tell.
    – D. Patrick
    Nov 29, 2012 at 14:44
  • Also, to make it more succinct, you could also have one function and just have it take a string parameter to specify the border for which you'd like to get the width (so you wouldn't need 4 functions). i.e., getBorderWidth($element, border). Better yet, add it to jQuery.fn so you can say, $element.getBorderWidth("right"), but I'm not that picky. I would like it to address the original question which was, "is there an easier way" and also be compatible with the current browsers.
    – D. Patrick
    Nov 29, 2012 at 14:46
  • @D.Patrick: Regarding the size difference, I didn't notice that until just now. This only happens in IE7 and I assume < IE7 (I don't have IE6). It seems in-consistant too as on thick the left border seems smaller by 1px but the right side looks like it is just off-set a little. The code I posted was only a rough example to get you started and not intended as a full solution by no means. However, I would assume one can check the version of IE somehow and update the constants accrodingly/dynamcially. I will look at it tonight and get back to you.
    – Nope
    Nov 29, 2012 at 15:43
0

Get Border width :

<script type="text/javascript">
$(document).ready(function(){
   var widthBorder = $("div").css("border");
   alert(widthBorder);
   //you can split between sintax 'px'
});
</script>
0

I have a solution using an additional inner container to circumvent the problem and calculate the real border withs of all sides of the container. So if having this additional inner container is possible in your situation, then this fiddle works for me in Chrome/FF/Safari/IE7/IE8 and with pixel border definitions as well as thin/medium/thick:

var BorderWrapper = {
    getBorderWidth: function(elem) {
        elem = jQuery(elem);
        var elemInner = jQuery(elem).find('.borderElemInner');

        var posOuter = elem.position();
        var posInner = elemInner.position();

        var result = {
            top:    posInner.top - posOuter.top - parseInt(elem.css('marginTop')),
            right:  0,
            bottom: 0,
            left:   posInner.left - posOuter.left - parseInt(elem.css('marginLeft'))
        };

        result.right = jQuery(elem).outerWidth() 
                     - jQuery(elemInner).outerWidth() 
                     - result.left;

        result.bottom = jQuery(elem).outerHeight() 
                      - jQuery(elemInner).outerHeight() 
                      - result.top;

        return result;
    }
};

It uses jQuery's ''.position()'', ''.outerWidth()'' and ''.outerHeight()'' and also accounts for margin of the outer container.

Maybe someone can verify this in IE9? I dont have it :)

0
<script type="text/javascript">
$(document).ready(function(){
   var widthBorder = $("div").css("border","5px");
  // you can increase your pixel size according to your requirement.
});
</script>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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