5

I need to get the real screen resolution using JavaScript (client-side at least), but having issues with both IE and Firefox as they tend to change this when you use the browser's built-in zoom.

How can this be done in a cross-browser friendly manner?

vanetten
  • 51
  • 1
  • 2

1 Answers1

0
function getDimension() {
  var width = 0, height = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    height = window.innerHeight;
    width = window.innerWidth;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    height = document.documentElement.clientHeight;
    width = document.documentElement.clientWidth;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    height = document.body.clientHeight;
    width = document.body.clientWidth;
  }
  window.alert( 'Width = ' + width + 'Height = ' + height);
}

or (jquery)

height    = $(window).height();
width    = $(window).width();
Bosworth99
  • 4,206
  • 5
  • 37
  • 52
  • as far as zoom goes = you could easily get the zoom level from the document.body.style.zoom (somthing like that) and work it into the equation. – Bosworth99 Mar 17 '11 at 17:36
  • I doubt that those values change with zooming in the first place, which is why I'd like to see the OP's code first - there must be something else going on – Pekka Mar 17 '11 at 17:37
  • Hmm - yeah I don't know for sure if they would change on zoom (be easy to find out tho ;). OP - code? – Bosworth99 Mar 17 '11 at 19:03
  • Thanks, but this won't work with most browser if you use the zoom (CTRL+/CTRL-) of the browser. Then the calculation will be relative to the zoom level which I cannot access. Quite annoying! – vanetten Mar 18 '11 at 13:21
  • Yes but you should be able to obtain the current zoom level via document.body.style.zoom - just multiply your current dimensions by the zoom factor and you should have your unzoomed resolution. Im in a car right now and cant test it... but i think it should work. – Bosworth99 Mar 18 '11 at 19:51
  • Problem is that document.body.style.zoom is not supported by all browsers (e.g. Firefox). So won't solve the case unfortunately! – vanetten Mar 28 '11 at 15:02
  • shouldnt the OR || be AND && ? || will be a bit more efficient but might lead to problems if some script defines document.body.clientHeight but not document.body.clientWidth in a browser that doesnt support the functionality. – Jascha Ehrenreich Dec 10 '13 at 14:05
  • and i just realized that the () around the || will lead to the full or being executed if the first part returns false, so there is no efficiency gain – Jascha Ehrenreich Dec 10 '13 at 14:09