Search code examples
javascriptjqueryhtmlcss

jQuery width getting wrong value


I have a problem with the jQuery method .width(). I have 4 different textareas that I need to resize according to the size of a div that contains them, so I call the method .width() to get the actual width of the div (which anyway is 100% of the window) but this method always gets the wrong value even after wrapping everything in a $(window).ready().

Here is the CSS:

#contCode{
    width: 100%;
    height: 500px;
    margin-top: 50px;
    float: left;
    padding: 0;
}
.codeArea{
    float: left;
    font-family: "Lucida Console", Monaco, monospace;
    height:100%;
    padding: 5px 0 0 5px;
    margin: 0;
    border-right: 1px solid black;
    border-bottom: 1px solid black;
    resize: none;
}

This is the HTML:

<div id="contCode">
    <textarea class="codeArea" placeholder="Put your code here"></textarea>
    <textarea class="codeArea" placeholder="Put your code here"></textarea>
    <textarea class="codeArea" placeholder="Put your code here"></textarea>
    <div class="codeArea"></div>
</div>

And this is the script:

$(window).ready(function (){
        var wi = $("#contCode").width(); 
        var wiTex;
        wiTex = (wi) / 4;
        $(".codeArea").width(wiTex);
    });

I have already tried with outerWidth and innerWith and got the same result.


Solution

  • I found two issues. The first I knew about

    1. You need to add box-sizing: border-box so that when you set the width of the boxes the border width is included. If you don't, a box set to 100px with a 1px border will actually be 102px wide.

    2. The second issue I found was with jQuery's .width() method. For some reason even when I told it manually to set to .width('100px') the boxes were being set to 112px. I changed it to use vanilla JavaScript instead.

    You can see from the demo below that the boxes align now.

    $(window).ready(function() {
      var wi = $("#contCode").width();
      var wiTex = (wi) / 4;
    
      document.querySelectorAll('.codeArea').forEach(function(node) {
        node.style.width = wiTex+'px'
      })
      
    });
    #contCode {
      width: 100%;
      height: 500px;
      margin-top: 50px;
      float: left;
      padding: 0;
    }
    .codeArea {
      float: left;
      font-family: "Lucida Console", Monaco, monospace;
      height: 100%;
      padding: 5px 0 0 5px;
      margin: 0;
      border-right: 1px solid black;
      border-bottom: 1px solid black;
      resize: none;
      background: #ccc;
      box-sizing: border-box;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="contCode">
      <textarea class="codeArea" placeholder="Put your code here"></textarea>
      <textarea class="codeArea" placeholder="Put your code here"></textarea>
      <textarea class="codeArea" placeholder="Put your code here"></textarea>
      <div class="codeArea">The result area</div>
    </div>