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
  • 19,976
  • 37
  • 134
  • 224

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
  • 45,891
  • 11
  • 86
  • 90
1

try this:

$(window).resize(function(){
   var newwidth = $(window).width();
   var newheight = $(window).height();      
   $("#element").css({"height": newheight, "width": newwidth });
});
Ram
  • 140,563
  • 16
  • 160
  • 190
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';
Francisco Valdez
  • 1,846
  • 13
  • 25
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
  • 19,881
  • 24
  • 93
  • 121
0

You can always just use CSS:

#element {width:100%; height:100%; position:fixed; }
Alexis Pigeon
  • 7,223
  • 11
  • 38
  • 44
Control Freak
  • 12,573
  • 28
  • 89
  • 143