javascript

How to detect screen or browser size in JavaScript

28 May , 2010  

Hey Folks,

 

Wonder how to you get the size of a visitor’s computer screen ? Yes, you might need it for some cases where you want to display content of your website correctly according to the screensize of the user’s computer, mobile, iPhone, Android device or any other smartphone.

You can detect screensize and the useable are of the screen by using the “screen” object.

screen.height shows the height of the screen
screen.width shows the width of the screen
screen.availHeight shows height but removes the interface height like taskbar, and browser menu etc.
screen.availWidth same as above,instead gives available width

screen is the object of window, but sometimes it might not work for all browsers. In that case we utilize the DOM. Using document.body you can get the height and width of the browser window.

I have written the following function, which will allow you to get height and width from different browsers.

<script type="text/javascript">
 
  function getWidth()
  {
    xWidth = null;
    if(window.screen != null)
      xWidth = window.screen.availWidth;
 
    if(window.innerWidth != null)
      xWidth = window.innerWidth;
 
    if(document.body != null)
      xWidth = document.body.clientWidth;
 
    return xWidth;
  }
function getHeight() {
  xHeight = null;
  if(window.screen != null)
    xHeight = window.screen.availHeight;
 
  if(window.innerHeight != null)
    xHeight =   window.innerHeight;
 
  if(document.body != null)
    xHeight = document.body.clientHeight;
 
  return xHeight;
}
 
</script>

Hope that helps

Stay Digified !!

Sachin Khosla

, , , ,


Comments are closed.

More in javascript (10 of 34 articles)


Hey Folks, When I started discussing web workers at SparkIT - 2010, I asked about it from the listeners. They ...