$("#my-div").css("height", $(window).outerHeight() + "px"); works with window.resize() but not $(window).load()

- 1 answer

Ad

As the title says, I'm trying to set the height of my div equal to the height of my viewport, but it only seems to proc when I resize the window and not when the page loads. The full code looks like this:

$(window).load(function() { resize_div(); });
window.onresize = function(event) { resize_div(); };

function resize_div() {
  $("#my-div").css("height", ($(window).outerHeight() - $("#menu").outerHeight()) + "px");
}

Why would it work on the window resize but now on window load? Thanks in advance for your help.

Update

Here are some other things that do not work:

$(document).ready(function() {
  resize_div();
});
window.onload = function(event) { resize_div(); };
$("#my-div").on("load", function() { resize_div(); });
setTimeout(resize_div(), 3000); # this was put inside $(document).ready()

Update 2

I added alerts to $(document).ready() and $(window).load() and both alerts were fired off before the timeline I'm embedding was loaded. So I think this might be an issue that's outside the scope of how I've phrased my question. The app I'm using - Shiny, which is sort of like Python's Flask module - is presumably loading the webpage and then dynamically injecting the divs into the body of the web page, which is why the function isn't working properly. However, adding a console.log to resize_div didn't result in any output either, so I don't think it's just an issue of the div not being present right away.

Ad

Answer

Ad

You should try this, this is working for me.

$(function(){
  resize_div();
  window.onresize = function(event) { resize_div(); };
});


function resize_div() {
  alert(0);
  $("#my-div").css("height", ($(window).outerHeight() - $("#menu").outerHeight()) + "px");
  $("#my-div").css("background-color","yellow");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="my-div">adfggfgsdgsfdgsfhfg</div>
<div id="menu" style="height:100px;">MenuDiv</div>

Ad
source: stackoverflow.com
Ad