Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS to detect browser width and height works in Chrome & Safari but not IE9 or FF9

Is there any reason why this code would work in Safari and Chrome but not IE or FF?

JS

function load(){
    w.value = window.outerWidth;
    h.value = window.outerHeight;
}

HTML

<input name="h" id="h" type="hidden" value="" />
<input name="w" id="w" type="hidden" value="" />

Click here for the entire page's source code

Thanks in advance for the assistance.

Edit: I figured out what was wrong. The following had to be added to the load function

var width = document.getElementById("w");
var height = document.getElementById("h");
width.value = window.outerWidth;
height.value = window.outerHeight;
like image 693
Eric Avatar asked Feb 07 '12 19:02

Eric


3 Answers

Internet Explorer use different properties to store the window size. Into Internet Explorer clientWidth/Height is inner window size (subtract the pixels used by scroll bar, menu etc) so try

function load(){
  if(window.outerHeight){
      w.value = window.outerWidth;
      h.value = window.outerHeight;
  }
  else {
      w.value = document.body.clientWidth;
      h.value = document.body.clientHeight; 
  }
}
like image 129
comu87 Avatar answered Nov 09 '22 02:11

comu87


Use jQuery methods which support almost all the browsers.

function load(){
    w.value = $(window).width();
    h.value = $(window).height();
}

Reference: width(), height()

like image 20
ShankarSangoli Avatar answered Nov 09 '22 01:11

ShankarSangoli


If you are using jQuery then I suggest using .width() and .height() because they will function properly cross-browser. window.outerWidth is not supported in IE 8 and below.

Here are some good docs for window.outerWidth: https://developer.mozilla.org/en/DOM/window.outerWidth

Using .width() and .height() will return a unit-less number (that is in pixels), if you want to get the exact height/width set (including px or em) then you can use .css('width') and .css('height').

like image 4
Jasper Avatar answered Nov 09 '22 02:11

Jasper