Click to See Complete Forum and Search --> : showing image after getting time


p_bucc
11-03-2003, 09:27 PM
hi there,

i am new here and to js. i want to show an image in relation to the time of the day or night. if it is afternoon i want to show a picture of the sun high in the sky.... i have seen some that will show only 2 times and images. i have tried to ad in some "else" tags. does anyone know if this has been done.


thank you

pyro
11-03-2003, 09:55 PM
You could try something like this:

<script type="text/javascript">
img1 = "day.jpg";
img2 = "night.jpg";
hours = new Date().getHours();
img = (hours < 12) ? img1 : img2;
document.write("<img src=\""+img+"\" width=\"50\" height=\"50\" alt=\"description\">");
</script>

Nayias
11-04-2003, 02:42 AM
hey the reason i am on this forum is too learn something about javascript, and i saw the script above.
i dont understand one part of it:

img = (hours < 12) ? img1 : img2;

whats the "?" thing doing? and the "img : img2"?
maybe someone can explain it?
or maybe give a link to a website where i can read about it?
thx

Gollum
11-04-2003, 03:10 AM
it's the conditional operator. C programmers will be v.familiar with its use.

it goes like this

cond_expr = (cond) ? (value_if_true) : (value_if_false);

It means:
1. evaluate the condition
2. If true, use the first value (before the colon)
3. If false, use the second value.

You can do pretty much the same thing with if(...) ... else... except it uses a lot less code.

pyro
11-04-2003, 07:08 AM
It's usualy just called the ternary operator. I couldn't find a good documented source to point you to, as it is more popular in other languages than it is in JavaScript. But, Gollum's explination is pretty good. It basically allows us to do some conditional matching with a lot less code than an if ... else condition.