Home > other >  How to match clientWidth in jQuery?
How to match clientWidth in jQuery?

Time:10-13

I can't find a way to get the same width using jQuery as I do with vanilla javascript.

I need to use jQuery, but the value that I need is 577px to be correct, which I'm only getting with vanilla js

document.getElementById('status_across_leagues').clientWidth  // returns 577

$('#status_across_leagues').width(); // returns 568

$('#status_across_leagues').innerWidth() // returns 588

$('#status_across_leagues').outerWidth() // returns 588

CodePudding user response:

You have to be mindful of padding and the presence of a scrollbar since these functions behave differently:

function ignores padding ignores scrollbar
.width() yes no
.innerWidth()/.outerWidth() no yes
.clientWidth no no

Therefore, Element.clientWidth will not match the behavior of any of those functions. If you need the exact number and must use jQuery, then you can just use $(el).prop('clientWidth'). See demo below.

function info(el) {
  const $el = $(el);
  $el.next().html(
    ' clientWidth: '   el.clientWidth  
    ' | width(): '   $el.width()  
    ' | innerWidth(): '   $el.innerWidth()  
    ' | outerWidth(): '   $el.outerWidth(true)  
    ' | prop(): '   $el.prop('clientWidth')
  )
}
$('div').each((i, el) => info(el))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="aDiv" style="width: 200px;">no padding, no scroll</div><pre></pre>
<div id="bDiv" style="padding: 5px; width: 200px;">padding only</div><pre></pre>
<div id="cDiv" style="overflow-y: scroll; width: 200px;">scroll only</div><pre></pre>
<div id="dDiv" style="padding: 5px; overflow-y: scroll; width: 200px;">padding and scroll</div><pre></pre>

  • Related