Merijn de Klerk
Merijn de Klerk

Reputation: 1023

window.load function doesn't work

I got a small problem with the JavaScript window on load function. The goal of the script is to make the height of my #headerdiv always equal to the size of the screen.

When I open the page it doesn't show my #headerdiv (I guess because the height isn't added by my JavaScript code). as soon as I resize my browser window the #headerdiv pups up and resizes to the height of the screen. So I guess its just the window load function which doesn't work? Anyone has a suggestion?

Here is my code:

Javascript:

<script>
$(function(){
    $(window).load(function(){ // On load
        $('#headerdiv').css({'height':(($(window).height()))  +'px'});
    });

    $(window).resize(function(){ // On resize
        $('#headerdiv').css({'height':(($(window).height()))+ 'px'});
    });
});     
</script>

Html + css:

<style>
    #headerdiv {width:100%; background:blue;padding:0;margin:0;overflow:auto;}​
</style>

<div id="headerdiv"></div>

Upvotes: 1

Views: 214

Answers (3)

Naftali
Naftali

Reputation: 146302

I would expand on antyrat's answer like so:
(there is no need to repeat code):

$(function(){

   $(window).resize(function(){ // On resize
       $('#headerdiv').css({'height':  $(window).height() + 'px'});
   }).trigger('resize'); //do the resize function on start

});

Upvotes: 0

SGS
SGS

Reputation: 181

Depending on whether you need to wait for all images to load, use either:

$(window).load(function(){ // On load
  $('#headerdiv').css({'height':(($(window).height()))  +'px'});
});

$(function(){
   $(window).resize(function(){ // On resize
      $('#headerdiv').css({'height':(($(window).height()))+ 'px'});
   });
});

or the answer given by @antyrat. You shouldn't wrap the $(window).load in a $(function()

Upvotes: 2

antyrat
antyrat

Reputation: 27765

You don't need there $( window ).load() as $(function(){ already do $( document ).ready() (see official docs for shortcuts)

So at this point your code already loaded. Just try:

$(function(){

   $('#headerdiv').css({'height':(($(window).height()))  +'px'});

   $(window).resize(function(){ // On resize
    $('#headerdiv').css({'height':(($(window).height()))+ 'px'});
   });

});

Upvotes: 5

Related Questions