Search code examples
jqueryhtmlwidth

Maintain Jquery Given Width on Resize


Using JQUERY I take the width of a table, divide it by 3 and assign the new width to some divs. This works great. However, when I resize the window (by dragging it) the widths don't continue to work (the divs are static, but myTable's width changes) . How can I get the new widths to be continually updated. Thanks.

<script>
$(document).ready(function() { 

var abc = $('#myTable').width();
var abc = abc/3;
var abc = abc + "px";

$('.facts').css("width",abc);
});
</script>

HTML

<table id='myTable'></table>
<div class='facts'></div>

Solution

  • You can use $(window).resize():

    <script>
    $(document).ready(function() { 
    
      function resizeDiv() {
        var abc = $('#myTable').width();
        var abc = abc/3;
        var abc = abc + "px";
        $('.facts').css("width",abc);
      }
      resizeDiv();
    
      $(window).resize(resizeDiv);
    
    });
    </script>
    

    See demo: https://jsfiddle.net/acdcjunior/aq4nmmwf/