0

I have the follow script, which does get the screen width/height, but it does so only after a page refresh;

function getWidth(){
    if(self.innerWidth){
        return self.innerWidth; 
    }

    if(document.documentElement && document.documentElement.clientHeight){
        return documentElement.clientWidth; 
    }

    if(document.body){
        return document.body.clientWidth;
    }
}

I would like to know if there are other alternatives to getting screen width/height of a browse as it happens.

robue-a7119895
  • 816
  • 2
  • 11
  • 31

1 Answers1

2

As someone has mentioned you can used the resize listener. Here is an example that I use in my own code:

<script>
        //allow global access to vars height and width, but protect namespace
        var Frame = {width:0,height:0};
        //function to get current height and width
        function getFrameSize() {              
            Frame.height = window.innerHeight;
            Frame.width = window.innerWidth;
        } 
        //set listeners to resize automatically 
        window.addEventListener('resize', getFrameSize);
        window.addEventListener('load', getFrameSize);             
    </script>

This will keep the actual height and width of the windows inner dimensions stored in Frame.height and Frame.width, and keep the values up to date by rechecking every time the window is resized.

Sam Redway
  • 7,605
  • 2
  • 27
  • 41