Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Javascript question

I'm totally new to javascript and I wanted to make something to learn more. I made this code:

function setImage(){
if(6 < getHours() < 10){
document.getElementById("idIframe").src = "../img/default/morning.jpeg";
}else if(10 > getHours() > 13){
document.getElementById("idIframe").src = "../img/default/lunch.jpeg";
}else if(13 > getHours() > 18){
document.getElementById("idIframe").src = "../img/default/dinner.jpeg";
}else{
document.getElementById("idIframe").src = "../img/default/evening.jpg";
}
}

In my html I got <script src="javascript/myscript.js"></script> and in the body tag I got onload="setImage" What I do is set a picture in an iframe depending on what time it is. iframe id is "idIframe" Something is wrong here...anybody know?

2 Answers

Lucas Krause
Lucas Krause
19,924 Points

Did you really defined the getHours() function? If you want to use the getHours() method of an instance of the global Date object you have to write (new Date()).getHours().

No. I din't. Would this be correct then?

(new Date()).getHours();
function setImage(){
if(getHours() < 10 && getHours() > 6){
document.getElementById("idIframe").src = "../img/default/morning.jpeg";
}else if(getHours() < 13 && getHours() > 10){
document.getElementById("idIframe").src = "../img/default/lunch.jpg";
}else if(getHours() > 18 && getHours() < 13){
document.getElementById("idIframe").src = "../img/default/dinner.jpg";
}else{
document.getElementById("idIframe").src = "../img/default/evening.jpg";
}
}
David Omar
David Omar
5,676 Points

In programming you can't use the < and > like you do in math class. if you need to have more than one comparison you have to use either &&(and) or ||(or) logical operators. && means both have to be true and || means only one of them needs to be true.

if(getHours() > 6 && getHours() < 10)
Lucas Krause
Lucas Krause
19,924 Points

Please note that the groups of && are evaluated before groups of || which means a>6 && b==2 || c==4 is evaluated as (a>6 && b==2) || (c==4) rather than (a>6) && (b==2 || c==4).

David Omar
David Omar
5,676 Points

yes good note and if you can't remember which has higher precedence just put the expression you want evaluated first n parenthesis.

Thanks! Are you guys sure there's nothing else wrong? No pictures will appear in my iframe though