View Full Version : need simple IF...ELSE for "var" in JS

08-08-2002, 01:51 AM
Simple JS for many of you...but not for me. Yes, I know I really need to learn these simple JS code writing staples. Getting a quick answer would be great. I know I have bookmarked many sites wherein I could learn this...but I don't have the time right now. Anyway...

I have the following in a portion of my JavaScript code:

var boxwidth=530;

I need to have it set to 530 for +/- 800px resolution, and 670 for 1024px and up.

I've used the following in my <head> for another script, but couldn't figure out the way to "if...else" it.

<script type="text/javascript">
var res =
(screen.width<=810) ? '800' :
(screen.width>810) ? '1024' : '';
document.write('<link rel="stylesheet" type="text/css" href="css' + res + '.css">');

08-08-2002, 02:04 AM
What you are trying to use is called the ternary operator. It's format is like this (for assiging values to variables)

variable = (condition) ? valueIfTrue : valueIfFalse;


var boxwidth = (screen.width<1024)? 530 : 670;

08-08-2002, 02:17 AM
I never thought I'd say this about a little line of JS code, but that is so cool! Just a simple little snipet does exactly what I need it to do.


:thumbsup: :thumbsup: :thumbsup:

08-08-2002, 03:33 AM
Ya, it is pretty cool. and it's not just for defining variables. for example
function happy()
alert("You are happy! =)");
function sad()
alert("You are sad! =(");

var mood = 'happy';
(mood == 'happy') ? happy() : sad(); Ok, silly example, but I think you get the point...:D