faqts : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 4 people (50%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

How do I detect the screen resolution, and then incorporate different style sheets depending on them

Apr 9th, 2008 20:29
ha mo, Abolfazl Shirazi, Victoria Draken,


Abolfazl Shirazi:
The main problem is to detect screen resolution. Incorporating 
different style sheets according to that will be easy.
You may want to change the class of some elements, according to screen 
resolution:
<!-- Begin -->
<html>
<head>
<style>
.bluetext {color:blue}
.redtext {color:red}
</style>
<script language="javascript">
function LoadStyle() {
	if (screen.width == 800 && screen.height == 600) {
		Text1.className = "bluetext"
	}
	if (screen.width == 1024 && screen.height == 768) {
		Text2.className = "redtext"
	}
}
</script>
</head>
<body onload="LoadStyle()">
<div id="Text1">This text should be blue if the screen resolution is 
800*600</div><br>
<div id="Text2">This text should be red if the screen resolution is 
1024*768</div><br>
</body>
</html>
<!-- End -->
Or you may want to change a specific style property of an element 
directly, according to screen resolution:
<!-- Begin -->
<html>
<head>
<script language="javascript">
function LoadStyle() {
	if (screen.width == 800 && screen.height == 600) {
		Text1.style.color = "blue"
	}
	if (screen.width == 1024 && screen.height == 768) {
		Text2.style.color = "red"
	}
}
</script>
</head>
<body onload="LoadStyle()">
<div id="Text1">This text should be blue if the screen resolution is 
800*600</div><br>
<div id="Text2">This text should be red if the screen resolution is 
1024*768</div><br>
</body>
</html>
<!-- End -->
At last you may want to change an external stylesheet link, according 
to screen resolution:
<!-- Begin -->
<html>
<head>
<link rel="stylesheet" id="MyTag">
<script language="javascript">
function LoadStyle() {
	if (screen.width == 800 && screen.height == 600) {
		MyTag.href = "blueback.css"
	}
	if (screen.width == 1024 && screen.height == 768) {
		MyTag.href = "redback.css"
	}
}
</script>
</head>
<body onload="LoadStyle()">
The File "blueback.css" will be used to this page if the screen 
resolution is 800*600.<br>
The File "redback.css" will be used to this page if the screen 
resolution is 1024*768.<br>
</body>
</html>
<!-- End -->
Works succesfully in IE6.
Have Fun!
http://www.businessian.com
http://www.healthinhealth.com
http://www.computerstan.com
http://www.financestan.com
http://www.healthstan.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.technologystan.com
http://www.zobab.com