Friday, October 15, 2010

Getting Browser's height and width using JavaScript which works in (IE,Firefox browsers )

                                            Getting the Browser's height and width is quite useful in many scenarios .Recently i  have got a requirement in one of the  project that is setting the background image based on  the browser width and height . But the problem is there are so many different types of browsers out there and you don't know which one the end user will be using. Another issue is the height and the width of different laptops and desktops available in the market which are having different resolutions .

                                        So most probably you are fine tuning your application based on the server or the PC or the laptop that you are using to develop. It will look perfectly fine until one day you decide to demo to your colleagues using a different laptop. All the layouts and alignments will be wrong. This happens if you hard code the height and width of the objects that you require in your site.

                                                  The best way for such applications is to get the height and the width of the client dynamically (using JavaScript) and then setting the height and the width of the objects dynamically. You can use the following JavaScript example to get the height and the width of the client.

                                             In my project requirement I need to set the back ground  right side  image based on browser width and height.So i have done this .please modify code according to your requirement.

<script type="text/javascript" language="javascript">
       window.onresize = SetGal
        function SetGal() {
       // debugger;
           var myWidth;
           var myHeight;
           if (typeof (window.innerWidth) == 'number') {
              //alert('non ie');
               myWidth = window.innerWidth;
               myHeight = window.innerHeight;
           else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
               myWidth = document.documentElement.clientWidth;
               myHeight = document.documentElement.clientHeight;
           else if (document.body && (document.body.clientWidth || document.body.clientHeight))
               myWidth = document.body.clientWidth-80;
               myHeight = document.body.clientHeight;
          // alert(myWidth);
           //  alert(myHeight);
      document.getElementById("gal_bg_2").style.height = myHeight + 'px';  // this element i am dynamicall setting based on browser width and height 
      document.getElementById("gal_bg_2").style.width = myWidth + 'px';