Wednesday, January 22, 2014

Screen Width and Height for iPhone, iPad, Android Tablets and Smartphones Using Javascript


When it comes to screen width and height, it is a bit tricky for tablet devices as the width and height vary according to the orientation of the tablet.

Therefore it is crucial to detect the screen dimension for websites that are sensitive to the width and height of the screen such as the sticky notes on the web page. The sticky note usually has to be accurate on the location on the web page or it may block important information in the web site.





The following are the Javascript codes that I used:

<script>

var clientWidth = document.getElementsByTagName("body")[0].clientWidth;
var clientHeight = document.getElementsByTagName("body")[0].clientHeight;
.
.
.
</script>


However, there is a problem here. The width and height will change whenever the user changes the orientation of the tablet. Here are improved codes after taking such scenario into consideration:

<script>

function checkDimension() {
   var clientWidth = document.getElementsByTagName("body")[0].clientWidth;
   var clientHeight = document.getElementsByTagName("body")[0].clientHeight;
.
.
.

</script>

<body onresize="checkDimension()"> .
.
.



Whenever the tablet changes the orientation, the onresize event on the browser will go to checkDimension() function. In that case, the Javascript is able to react to any changes to screen size and orientation.

No comments:

Post a Comment