View Full Version : Using Javascript to apply CSS if criteria met

09-12-2008, 04:27 PM
Hey guys,

Another JavaScript query for you. I have a design that needs to be centred vertically in the middle of the user's browser. I can do this easily enough with just CSS and it works like a dream in resolutions 1280x1024 and above.

However, the CSS does not work well on any resolution less than that and causes clipping errors. This is mainly due to the layout already being vertically centered by accident due to the resolution limitations.

So what I'd like to do, is write some JavaScript that will check a user's screen resolution, and will apply the Vertical Centering CSS if the user's screen resolution is 1280x1024 and above.

I can write the JavaScript to check the user's screen resolution and redirect them to another HTML page if their screen resolution is less or greater than the defined dimensions, however I cannot figure out how to reference CSS into the script.

Please help!

09-12-2008, 05:22 PM
This should be nice and simple -

I assume you're using innerHeight/innerWidth (or/as-well-as clientWidth/clientheight) to get the client X/Y.

Somthing like this:

var width = window.innerWidth;
var height = window.innerHeight;
var width = document.documentElement.clientWidth;
var height = document.documentElement.clientHeight;

if(height>=768 && width>=1024){
/Do Somthing
//Do Somthing Else

What's the CSS you need to alter based on the resolution? most CSS properties can be accessed through

<element>.style.<property> = <newValue>

but if you give me what it is you actually need to change, I can give you exact syntax ;)

09-12-2008, 06:01 PM
Thanks for the reply Mikebert4. Here is the CSS I use to position the layout vertically.

#horizon {