title: How to dynamically re-evaluate a function with jQuery?
body: <p>I've setup the following jQuery function to add a negative left margin to a <code>&lt;div&gt;</code> element</p>
  
  <pre><code>$(document).ready(function(){
  
      var docwidth = $(document).width();
      var herowidth = $('.element-hero').width();
      var leftmargin = docwidth - herowidth;
  
      $('.element-hero').css({ "margin-left": -leftmargin,});
  
  });
  </code></pre>
  
  <p>As you can see, it gets the document width, the <code>&lt;div class="element-hero"&gt;</code> width, and applies to the latter a negative left margin equal to the difference between these two values.</p>
  
  <p>It works fine, until I try to resize the browser window; I need the value of the left margin to be dynamically re-calculated when the window is resized (without reloading, of course). </p>
  
  <p>Right now, if we assume, in example, initial values of <code>docwidth = 1200px</code> and <code>herowidth = 900px</code>, the left margin is set to <code>-300px</code>; If I resize the window to have <code>docwidth = 1400px</code>, I expect to have a margin of <code>-500px</code>, but this is not what really happens, the original calculated value of <code>-300px</code> is kept until I manually reload the window.</p>
  
  <p>From what I get, the problem is that using <code>.ready()</code> runs the script once after the document is fully loaded; I also need this value to be calculated everytime that the window is resized, and be updated accordingly.</p>
  
  <p>How should I modify this code?</p>