Thursday, April 16, 2009

How to dynamically change attribute (e.g height) of HTML tag based on screen resolution using javascript?


Sometimes we may need to specify the attributes such as height and width of HTML tag in pixels instead of specifying it using percentage.
In this case, the HTML page will appear differently in different screen resolution of the user's computer monitor.

To avoid this issue we have to dynamically change the attributes of the HTML tags based on the screen resolution. It can be done using javascript.
In javascript, screen resolution can be identified using screen.height and screen.width.

Find below the sample code which explains how to dynamically change the attributes based on Screen resolution.

<html>
<head>
<script language="javascript">
function adjustHeight()
{
var ref_height='768';
var actual_height=screen.height;
var m_factor=actual_height/ref_height;

var h1=document.getElementById('id1').getAttribute('height');
h1=h1*m_factor;
document.getElementById('id1').setAttribute('height',h1)
}
</script> 

</head>
<body onLoad="adjustHeight();">
<table >
<tr height="80" id="id1" bgcolor="#009900"><td> </td></tr>

</table>

</body>
</html>



Explanation for above code:
- Initial design time height for TR tag is 80.
- onLoad event of body tag calls javascript function adjustHeight()which will change height of this TR tag based on height of user's screen.
- adjustHeight will find a multiplying factor based on predefined reference height and the height of the user's screen. And it will use setAttribute to change the height of TR tag based on this multiplying factor.
More Articles...

No comments:

Search This Blog