Determining the height and width of a <div> dynamically

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    Determining the height and width of a <div> dynamically

    Hi there!

    I've created a "message" box that consists of a <div> with a bunch of information in it and some buttons (which could be "ok", "yes", "no", "cancel"... ). It's dynamically created with some .NET code on the server.

    Because the message information that is within this <div> is dynamic, it can be several lines long...also the message box <div> can be variable widths wide as well. Therefore, I need a Dependable way to dynamically retrieve the width and height of the <div> in order to properly center it in the middle of the browser.

    I have used:
    [code=javascript]
    var panelHeight = document.getEle mentById(nameOf MessageBoxWindo w).clientHeight ;
    var panelWidth = document.getEle mentById(nameOf MessageBoxWindo w).clientWidth;
    [/code]

    However this code only seems to work in certain circumstances, and others doesn't work at all (using firebug I discovered that these two values were always 0 for some weird reason).

    In order to find the width of the <div>, I set the <div>'s style width dynamically with my .NET code and then used the following code:
    [code=javascript]
    var styleWidth = panel.style.wid th;
    var panelWidth = Number(styleWid th.replace(/px/,""));
    [/code]

    This works, however it feels like a bit of a "workaround " to me. Also, this solution doesn't help me find the height of the <div>.

    Does anyone know what might be the cause to the element.clientW idth to always be 0?
    Does anyone know of another way to dynamically determine the height and width of the <div>?

    Thanks for your time,

    -Frinny
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    hi frinny,

    have a look whether this thread helps ... and here is another link ;)

    kind regards

    Comment

    • Frinavale
      Recognized Expert Expert
      • Oct 2006
      • 9749

      #3
      Originally posted by gits
      hi frinny,

      have a look whether this thread helps ... and here is another link ;)

      kind regards
      Thanks Gits,
      I'm looking into the offsetHeight and offsetWidth now.
      I think I've tried this before, I'll get back to you to let you know if it helps.


      -Frinny

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Originally posted by Frinavale
        Thanks Gits,
        I'm looking into the offsetHeight and offsetWidth now.
        I think I've tried this before, I'll get back to you to let you know if it helps.


        -Frinny
        The offsetHeight and offsetWidth did not work.

        Comment

        • gits
          Recognized Expert Moderator Expert
          • May 2007
          • 5390

          #5
          i just tested it in IE6 and FF and it worked without problems ... may be you could post a html-example that demonstrates your problem?

          kind regards

          Comment

          • Frinavale
            Recognized Expert Expert
            • Oct 2006
            • 9749

            #6
            Originally posted by gits
            i just tested it in IE6 and FF and it worked without problems ... may be you could post a html-example that demonstrates your problem?

            kind regards
            It's really complicated because of the auto generated stuff that the .NET code does.

            Basically I have a control that handles uploading of pictures, if the picture is not uploaded properly a message window is supposed to be displayed in the middle of the page. This is the message window that does not center (because the clientHeight and offsetHeight of this <div> are 0).

            The control that handles the uploading of the pictures is buried deep within nested <divs>.

            I have other message box <div> windows as well on the page (which are also buried within other <div>s but not so deep) and they center properly.

            I'll see what I can figure out to try and easily show you the problem....

            The worst part is that it works in most cases, it's just this deeply buried message box that's the problem.

            -Frinny

            Comment

            • mmurph211
              New Member
              • Jan 2008
              • 13

              #7
              Try these two functions out:
              http://www.matts411.co m/webdev/width_and_heigh t_getter_functi ons_for_html_el ements

              Just wrote them. Should work but have yet to do enough testing to prove that they work 100% of the time.

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #8
                Originally posted by mmurph211
                Try these two functions out:


                Just wrote them. Should work but have yet to do enough testing to prove that they work 100% of the time.
                In the following code you check to see if the element (in my case the <div> that is my message box) has a current style display of "none.
                Then you grab the offsetWidth of that element:

                [CODE=JAVASCRIPT]
                if(el.currentSt yle["display"] == "none")
                return 0;
                var widthCSS = el.currentStyle["width"];
                var bRegex = /thin|medium|thi ck/; // regex for css border width keywords
                width = el.offsetWidth; // currently the width including padding + border
                [/CODE]

                In my code I simply set the display of the element to be "block"...becau se I discovered quickly that both the offsetWidth and the clientWidth will be 0 if the element's display value is none.

                This is what I have right now:
                [code=JavaScript]

                function ShowWindowAndIn nerWindow(nameO fWindow,nameOfI nnerWindow)
                {


                var panel = document.getEle mentById(nameOf Window);
                //**Originally I had set the panel to be hidden while I dealt with moving the message box to the middle of the screen... see **comment continuation at the bottom.
                //panel.style.vis ibility = 'hidden';

                //Here I set the panel to have a display of 'block' because if the panel has a display of 'none' you cannot get the clientWidth or offsetWidth values
                panel.style.dis play = 'block';

                //I make sure that the panel is positioned absolute
                panel.position = 'absolute';

                //This inner stuff, just ignore...
                var innerPanel = document.getEle mentById(nameOf InnerWindow);
                innerPanel.styl e.display = 'block';

                //here I grab the offsetWidth...b ut it doesn't work all the time....
                var widthOfPanel = panel.offsetWid th;
                //sooo here I hard code a width value
                widthOfPanel=40 0;

                //The offsetHeight doesn't work all the time either, but it isn't so apparent when it doesn't work, so I don't care about setting a hard coded value.
                var heightOfPanel = panel.offsetHei ght;

                //determining how far from the left and the top that the browser should be drawn at in order to center it.
                var left = Number(BrowserW idth())/2 - (widthOfPanel/2);
                var top = Number(BrowserH eight())/2 - (heightOfPanel/2);

                //Centering
                if(document.doc umentElement)
                {
                var topOffset = document.docume ntElement.scrol lTop + top;
                var leftOffset = document.docume ntElement.scrol lLeft + left;
                panel.style.top = topOffset + "px";
                panel.style.lef t = leftOffset + "px";
                }
                else if(document.bod y)
                {
                var topOffset = document.body.s crollTop + top;
                var leftOffset = document.body.s crollLeft + left;
                panel.style.top = topOffset + "px";
                panel.style.lef t = leftOffset + "px";
                }
                else
                {

                }
                //** comment continued from the above ** comment
                //**Apparently when you set the panel to visibility of "hidden" then set it back to "visible", my buttons don't appear until I drag the message box
                //panel.style.vis ibility = 'visible';
                return false;
                }
                [/code]

                Your code is much more complicated than mine, but you rely on the offsetWidth value as I do...this value is not working for me....it always returns 0 in the case that it is buried deep within other <divs>......... ......

                Comment

                • mmurph211
                  New Member
                  • Jan 2008
                  • 13

                  #9
                  If has a display value of none I return 0. I don't check the offsetWidth unless it has a display value of block or something != none

                  [CODE=javascript]
                  if(el.currentSt yle["display"] == "none")
                  return 0;
                  [/CODE]

                  also clientWidth will return 0 in IE when the div's width is not set or is set to 'auto'

                  try this with the functions I wrote:

                  [CODE=javascript]
                  function ShowWindowAndIn nerWindow(nameO fWindow,nameOfI nnerW indow)
                  {

                  var panel = document.getEle mentById(nameOf Window);
                  //**Originally I had set the panel to be hidden while I dealt with moving the message box to the middle of the screen... see **comment continuation at the bottom.
                  //panel.style.vis ibility = 'hidden';

                  //Here I set the panel to have a display of 'block' because if the panel has a display of 'none' you cannot get the clientWidth or offsetWidth values
                  panel.style.dis play = 'block';

                  //I make sure that the panel is positioned absolute
                  panel.position = 'absolute';

                  //This inner stuff, just ignore...
                  var innerPanel = document.getEle mentById(nameOf InnerWindow);
                  innerPanel.styl e.display = 'block';

                  var widthOfPanel = getWidth(panel, true, true);
                  var heightOfPanel = getHeight(panel , true, true);

                  //determining how far from the left and the top that the browser should be drawn at in order to center it.
                  var left = Number(BrowserW idth())/2 - (widthOfPanel/2);
                  var top = Number(BrowserH eight())/2 - (heightOfPanel/2);

                  //Centering
                  if(document.doc umentElement)
                  {
                  var topOffset = document.docume ntElement.scrol lTop + top;
                  var leftOffset = document.docume ntElement.scrol lLeft + left;
                  panel.style.top = topOffset + "px";
                  panel.style.lef t = leftOffset + "px";
                  }
                  else if(document.bod y)
                  {
                  var topOffset = document.body.s crollTop + top;
                  var leftOffset = document.body.s crollLeft + left;
                  panel.style.top = topOffset + "px";
                  panel.style.lef t = leftOffset + "px";
                  }
                  else
                  {

                  }
                  //** comment continued from the above ** comment
                  //**Apparently when you set the panel to visibility of "hidden" then set it back to "visible", my buttons don't appear until I drag the message box
                  //panel.style.vis ibility = 'visible';
                  return false;
                  }
                  [/CODE]

                  Comment

                  • Frinavale
                    Recognized Expert Expert
                    • Oct 2006
                    • 9749

                    #10
                    Originally posted by mmurph211
                    If has a display value of none I return 0. I don't check the offsetWidth unless it has a display value of block or something != none

                    [CODE=javascript]
                    if(el.currentSt yle["display"] == "none")
                    return 0;
                    [/CODE]

                    also clientWidth will return 0 in IE when the div's width is not set or is set to 'auto'

                    try this with the functions I wrote:
                    ...
                    I do not set the width or height values of my <div>s because are adjusted according to the content...in other words, they have a style="width:au to;height:auto; " by default in order to fit according to the content requirements.

                    Since I do not have a style set for my <div>...
                    [code=javascript]
                    var height;
                    el = (typeof(el) == "string") ? document.getEle mentById(el) : el;

                    if(window.getCo mputedStyle) {
                    var style = document.defaul tView.getComput edStyle(el, null);
                    if(style.getPro pertyValue("dis play") == "none")
                    return 0;
                    height = parseInt(style. getPropertyValu e("height"));
                    //height will always be 0
                    [/code]
                    height will always be 0......

                    Comment

                    • Frinavale
                      Recognized Expert Expert
                      • Oct 2006
                      • 9749

                      #11
                      Originally posted by Frinavale
                      I do not set the width or height values of my <div>s because are adjusted according to the content...in other words, they have a style="width:au to;height:auto; " by default in order to fit according to the content requirements.

                      Since I do not have a style set for my <div>...
                      [code=javascript]
                      var height;
                      el = (typeof(el) == "string") ? document.getEle mentById(el) : el;

                      if(window.getCo mputedStyle) {
                      var style = document.defaul tView.getComput edStyle(el, null);
                      if(style.getPro pertyValue("dis play") == "none")
                      return 0;
                      height = parseInt(style. getPropertyValu e("height"));
                      //height will always be 0
                      [/code]
                      height will always be 0......
                      Actually, running it through FireBug, height is set to "auto"...

                      Comment

                      • mmurph211
                        New Member
                        • Jan 2008
                        • 13

                        #12
                        That's not what I'm getting. Are you in quirks mode?


                        I made a test file:
                        [code=html]
                        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
                        <html>
                        <head>
                        <title>Get width/height - Test Page</title>[/code]
                        [code=javascript]
                        <script type="text/javascript">
                        //<![CDATA[

                        function getWidth(/* Object */ el, /* boolean */ includePadding, /* boolean */ includeBorder) {
                        var width;
                        el = (typeof(el) == "string") ? document.getEle mentById(el) : el;

                        if(window.getCo mputedStyle) { // FF, Safari, Opera
                        var style = document.defaul tView.getComput edStyle(el, null);
                        if(style.getPro pertyValue("dis play") == "none")
                        return 0;
                        width = parseInt(style. getPropertyValu e("width"));

                        if(navigator.us erAgent.toLower Case().indexOf( "opera") != -1) {
                        // opera includes the padding and border when reporting the width/height - subtract that out
                        width -= parseInt(style. getPropertyValu e("padding-left"));
                        width -= parseInt(style. getPropertyValu e("padding-right"));
                        width -= parseInt(style. getPropertyValu e("border-left-width"));
                        width -= parseInt(style. getPropertyValu e("border-right-width"));
                        }

                        if(includePaddi ng) {
                        width += parseInt(style. getPropertyValu e("padding-left"));
                        width += parseInt(style. getPropertyValu e("padding-right"));
                        }

                        if(includeBorde r) {
                        width += parseInt(style. getPropertyValu e("border-left-width"));
                        width += parseInt(style. getPropertyValu e("border-right-width"));
                        }
                        } else { // IE
                        if(el.currentSt yle["display"] == "none")
                        return 0;
                        var widthCSS = el.currentStyle["width"];
                        var bRegex = /thin|medium|thi ck/; // regex for css border width keywords
                        width = el.offsetWidth; // currently the width including padding + border

                        if(!includeBord er) {
                        var borderLeftCSS = el.currentStyle["borderLeftWidt h"];
                        var borderRightCSS = el.currentStyle["borderRightWid th"];
                        var temp = document.create Element("DIV");
                        if(!bRegex.test (borderLeftCSS) ) {
                        temp.style.widt h = borderLeftCSS;
                        el.parentNode.a ppendChild(temp );
                        width -= Math.round(temp .offsetWidth);
                        el.parentNode.r emoveChild(temp );
                        } else if(bRegex.test( borderLeftCSS)) {
                        if(el.offsetWid th > el.clientWidth && el.currentStyle["borderLeftStyl e"] != "none") {
                        temp.style.widt h = "10px";
                        temp.style.bord er = borderLeftCSS + " " + el.currentStyle["borderLeftStyl e"] + " #000000";
                        el.parentNode.a ppendChild(temp );
                        width -= Math.round((tem p.offsetWidth-10)/2);
                        el.parentNode.r emoveChild(temp );
                        }
                        }
                        if(!bRegex.test (borderRightCSS )) {
                        temp.style.widt h = borderRightCSS;
                        el.parentNode.a ppendChild(temp );
                        width -= Math.round(temp .offsetWidth);
                        el.parentNode.r emoveChild(temp );
                        } else if(bRegex.test( borderRightCSS) ) {
                        if(el.offsetWid th > el.clientWidth && el.currentStyle["borderRightSty le"] != "none") {
                        temp.style.widt h = "10px";
                        temp.style.bord er = borderRightCSS + " " + el.currentStyle["borderRightSty le"] + " #000000";
                        el.parentNode.a ppendChild(temp );
                        width -= Math.round((tem p.offsetWidth-10)/2);
                        el.parentNode.r emoveChild(temp );
                        }
                        }
                        }

                        if(!includePadd ing) {
                        var paddingLeftCSS = el.currentStyle["paddingLef t"];
                        var paddingRightCSS = el.currentStyle["paddingRig ht"];
                        var temp = document.create Element("DIV");
                        temp.style.widt h = paddingLeftCSS;
                        el.parentNode.a ppendChild(temp );
                        width -= Math.round(temp .offsetWidth);
                        temp.style.widt h = paddingRightCSS ;
                        width -= Math.round(temp .offsetWidth);
                        el.parentNode.r emoveChild(temp );
                        }
                        }

                        return width;
                        }

                        function getHeight(/* Object */ el, /* boolean */ includePadding, /* boolean */ includeBorder) {
                        var height;
                        el = (typeof(el) == "string") ? document.getEle mentById(el) : el;

                        if(window.getCo mputedStyle) { // FF, Safari, Opera
                        var style = document.defaul tView.getComput edStyle(el, null);
                        if(style.getPro pertyValue("dis play") == "none")
                        return 0;
                        height = parseInt(style. getPropertyValu e("height"));

                        if(navigator.us erAgent.toLower Case().indexOf( "opera") != -1) {
                        // opera includes the padding and border when reporting the width/height - subtract that out
                        height -= parseInt(style. getPropertyValu e("padding-top"));
                        height -= parseInt(style. getPropertyValu e("padding-bottom"));
                        height -= parseInt(style. getPropertyValu e("border-top-width"));
                        height -= parseInt(style. getPropertyValu e("border-bottom-width"));
                        }

                        if(includePaddi ng) {
                        height += parseInt(style. getPropertyValu e("padding-top"));
                        height += parseInt(style. getPropertyValu e("padding-bottom"));
                        }

                        if(includeBorde r) {
                        height += parseInt(style. getPropertyValu e("border-top-width"));
                        height += parseInt(style. getPropertyValu e("border-bottom-width"));
                        }
                        } else { // IE
                        if(el.currentSt yle["display"] == "none")
                        return 0;
                        var heightCSS = el.currentStyle["height"];
                        var bRegex = /thin|medium|thi ck/; // regex for css border width keywords
                        height = el.offsetHeight ; // currently the height including padding + border

                        if(!includeBord er) {
                        var borderTopCSS = el.currentStyle["borderTopWidth "];
                        var borderBottomCSS = el.currentStyle["borderBottomWi dth"];
                        var temp = document.create Element("DIV");
                        if(!bRegex.test (borderTopCSS)) {
                        temp.style.widt h = borderTopCSS;
                        el.parentNode.a ppendChild(temp );
                        height -= Math.round(temp .offsetWidth);
                        el.parentNode.r emoveChild(temp );
                        } else if(bRegex.test( borderTopCSS)) {
                        if(el.offsetHei ght > el.clientHeight && el.currentStyle["borderTopStyle "] != "none") {
                        temp.style.widt h = "10px";
                        temp.style.bord er = borderTopCSS + " " + el.currentStyle["borderTopStyle "] + " #000000";
                        el.parentNode.a ppendChild(temp );
                        height -= Math.round((tem p.offsetWidth-10)/2);
                        el.parentNode.r emoveChild(temp );
                        }
                        }
                        if(!bRegex.test (borderBottomCS S)) {
                        temp.style.widt h = borderBottomCSS ;
                        el.parentNode.a ppendChild(temp );
                        height -= Math.round(temp .offsetWidth);
                        el.parentNode.r emoveChild(temp );
                        } else if(bRegex.test( borderBottomCSS )) {
                        if(el.offsetHei ght > el.clientHeight && el.currentStyle["borderBottomSt yle"] != "none") {
                        temp.style.widt h = "10px";
                        temp.style.bord er = borderBottomCSS + " " + el.currentStyle["borderBottomSt yle"] + " #000000";
                        el.parentNode.a ppendChild(temp );
                        height -= Math.round((tem p.offsetWidth-10)/2);
                        el.parentNode.r emoveChild(temp );
                        }
                        }
                        }

                        if(!includePadd ing) {
                        var paddingTopCSS = el.currentStyle["paddingTop "];
                        var paddingBottomCS S = el.currentStyle["paddingBot tom"];
                        var temp = document.create Element("DIV");
                        temp.style.widt h = paddingTopCSS;
                        el.parentNode.a ppendChild(temp );
                        height -= Math.round(temp .offsetWidth);
                        temp.style.widt h = paddingBottomCS S;
                        height -= Math.round(temp .offsetWidth);
                        el.parentNode.r emoveChild(temp );
                        }
                        }

                        return height;
                        }


                        function ShowWindowAndIn nerWindow(nameO fWindow,nameOfI nnerWindow)
                        {

                        var panel = document.getEle mentById(nameOf Window);

                        //**Originally I had set the panel to be hidden while I dealt with moving the message box to the middle of the screen... see **comment continuation at the bottom.

                        //panel.style.vis ibility = 'hidden';

                        //Here I set the panel to have a display of 'block' because if the panel has a display of 'none' you cannot get the clientWidth or offsetWidth values
                        panel.style.dis play = 'block';

                        //I make sure that the panel is positioned absolute

                        panel.position = 'absolute';

                        //This inner stuff, just ignore...
                        var innerPanel = document.getEle mentById(nameOf InnerWindow);
                        innerPanel.styl e.display = 'block';

                        var widthOfPanel = getWidth(panel, true, true);
                        var heightOfPanel = getHeight(panel , true, true);

                        // for testing
                        alert("getWidth (panel, true, true): " + getWidth(panel, true, true) + " \n getHeight(panel , true, true): " + getHeight(panel , true, true));

                        /*
                        //determining how far from the left and the top that the browser should be drawn at in order to center it.
                        var left = Number(BrowserW idth())/2 - (widthOfPanel/2);
                        var top = Number(BrowserH eight())/2 - (heightOfPanel/2);

                        //Centering
                        if(document.doc umentElement)
                        {
                        var topOffset = document.docume ntElement.scrol lTop + top;
                        var leftOffset = document.docume ntElement.scrol lLeft + left;
                        panel.style.top = topOffset + "px";
                        panel.style.lef t = leftOffset + "px";
                        }
                        else if(document.bod y)
                        {
                        var topOffset = document.body.s crollTop + top;
                        var leftOffset = document.body.s crollLeft + left;
                        panel.style.top = topOffset + "px";
                        panel.style.lef t = leftOffset + "px";
                        }
                        else
                        {

                        }
                        //** comment continued from the above ** comment
                        //**Apparently when you set the panel to visibility of "hidden" then set it back to "visible", my buttons don't appear until I drag the message box
                        //panel.style.vis ibility = 'visible';
                        return false;
                        */
                        }

                        //]]>
                        </script>[/javascript]
                        [code=html]
                        </head>
                        <body>[/code]

                        [code=javascript]
                        <script type="text/javascript">
                        //<![CDATA[

                        var testMsgs = ["OK", "Yes", "No", "Cancel"];

                        function dynamicFunction () {

                        for(i=0; i<testMsgs.leng th; i++) {
                        var outerDiv = document.create Element('DIV');
                        outerDiv.id = "outer";

                        var innerDiv = document.create Element('DIV');
                        innerDiv.id = "inner";
                        innerDiv.innerH TML = testMsgs[i];

                        outerDiv.append Child(innerDiv) ;
                        document.body.a ppendChild(oute rDiv);
                        ShowWindowAndIn nerWindow("oute r", "inner");
                        document.body.r emoveChild(oute rDiv);
                        }

                        }

                        window.onload = dynamicFunction ;

                        //]]>
                        </script>[/code]
                        [code=html]
                        </body>
                        </html>[/code]
                        Last edited by Frinavale; Mar 29 '08, 03:21 PM. Reason: added [code] tags

                        Comment

                        • Frinavale
                          Recognized Expert Expert
                          • Oct 2006
                          • 9749

                          #13
                          Originally posted by mmurph211
                          That's not what I'm getting. Are you in quirks mode?


                          I made a test file:
                          ...
                          Thanks a lot for your help Mmurph.
                          Your solution will works fine.
                          I still have a problem determining the height the <div> in "particular " cases (when it is buried deep within other <div>s). I'm not sure why I'm having this problem because the <div> has a position of absolute.

                          I don't know what you mean by "quirks mode". I simply test my stuff in IE6, IE7 (which is the one that is causing the problem), Safari, Firefox, and Opera. I find Firefox's Firebug to be very helpful in debugging JavaScript so I tend to use it the most.

                          You have helped me in suggesting (via your code) that I should set the style's width and use that in order to get around the problem for the <div>s that are buried.

                          As a result, my message boxes are always positioned horizontally in the middle of the screen. This wasn't the case before. Thanks again for helping me with that solution.

                          I am still having problems positioning the box vertically (only when the <div> is buried deep within my .NET user controls on the page and online in IE7). I can live with it not properly centering vertically because most of these message boxes (buried deep) don't contain much data so it doesn't matter that they are a bit off. The ones that do contain a lot of data (so it's important to center them vertically) are not buried and work fine.

                          Thank you so much for your time and help Mmurph!

                          :)

                          -Frinny

                          Comment

                          • drhowarddrfine
                            Recognized Expert Expert
                            • Sep 2006
                            • 7434

                            #14
                            Originally posted by Frinavale
                            I'm not sure why I'm having this problem because the <div> has a position of absolute.
                            Didn't read all this but, just to add if it helps, absolutely positioned elements are removed from the normal flow and will collapse to zero if there are no contents or no height/width set.
                            I don't know what you mean by "quirks mode".
                            Quirks mode is what IE defaults to when a page has no doctype, has any junk before the doctype, or has an incorrect/incomplete doctype. It will follow the broken box model it set in 1996 and won't behave like any other browser. This will throw off margins/padding/width/height/and the color purple.

                            Comment

                            Working...