5

I've looked at many questions regarding this subject and can not seem to find out what is wrong with my code. Any help would be greatly appreciated!

$(window).resize(function(){
   var newwidth = $(window).innerWidth();
   var newheight = $(window).innerHeight();      
   $("#element").height(newheight).width(newwidth);
       });

I'm trying to resize #element to the same height and width as the window if the window is resized.

d-_-b
  • 21,536
  • 40
  • 150
  • 256

5 Answers5

13

About .innerWidth(), from docs:

This method is not applicable to window and document objects; for these, use .width() instead.

There is same note for .innerHeight() also.

So you need to use .width() and .height():

$(window).resize(function(){
    var newwidth = $(window).width();
    var newheight = $(window).height();      
    $("#element").height(newheight).width(newwidth);
});
Engineer
  • 47,849
  • 12
  • 88
  • 91
1

try this:

$(window).resize(function(){
   var newwidth = $(window).width();
   var newheight = $(window).height();      
   $("#element").css({"height": newheight, "width": newwidth });
});
Ram
  • 143,282
  • 16
  • 168
  • 197
1

In plain Javascript you can do this:

    var viewportwidth;
    var viewportheight;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

    if (typeof window.innerWidth != 'undefined')
    {
        viewportwidth = window.innerWidth,
        viewportheight = window.innerHeight
    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

    else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
    {
         viewportwidth = document.documentElement.clientWidth,
         viewportheight = document.documentElement.clientHeight
    }

    // older versions of IE

    else
    {
         viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
         viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }
    var mydiv = document.getElementById("element");
    mydiv.style.height=viewportheight'px';
    mydiv.style.width=viewportwidth+'px';
Paco Valdez
  • 1,915
  • 14
  • 26
1

jsFiddle

 $(window).resize(function(){
var newwidth = $(window).width();
var newheight = $(window).height();      
$("#element").height(newheight).width(newwidth);
  });​

both works for me

update

 $(window).resize(function(){
var newwidth = $(window).innerWidth();
var newheight = $(window).innerHeight();      
$("#element").height(newheight).width(newwidth);
  });​
Mina Gabriel
  • 23,150
  • 26
  • 96
  • 124
0

You can always just use CSS:

#element {width:100%; height:100%; position:fixed; }
Alexis Pigeon
  • 7,423
  • 11
  • 39
  • 44
Control Freak
  • 12,965
  • 30
  • 94
  • 145