Can someone please help me fix this code? It was suppose to display an image at different time of the day based on the day of the week. When i changed the day to monday it will work but it will still work if i change it to tuesday and it’s not even tuesday.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img id="image">
</body>
<script>
var date = new Date();
var day = date.getDay();
var hour = date.getHours();
var minutes = date.getMinutes();
var img;
if (day = 0 && day < 6) {
if (hour = 8) {
if (minutes > 23) {
img = "image1";
} else {
img = "image2";
}
} else if (hour > 8 && hour < 14) {
img = "image1";
} else if (hour = 2) {
if (minutes < 43) {
img = "image1";
}
} else {
img = "image2";
}
} else {
img = "image2";
}
(function() {
document.getElementById("image").src = img + ".jpg";
})()
</script>
</html>
When comparing two things to see if they are equal, use ===
For example:
var foo = "foo";
var bar = "bar";
if (foo === bar) {
console.log("Something is strange with this universe.");
} else {
console.log("Nothing to see here, move along.");
}
This page should help much more than me posting code. Something as basic as operators is very important for you to understand, not only for JavaScript but for a great many other languages as well.
IMHO starting with a simple script at first is a good idea. That’s how I prefer to work up a script. Working - tweak until it breaks - fix - rinse, repeat.
Notice the getImageSourceByDate() and the return lines.
The getImageSourceByDate() line is “calling” a function named “getImageSourceByDate”, but your code (as it is) has no such function.
If you open your browsers dev tools console you may see an “undefined” error message that could help point you to the problem.
Sometimes functions only “do stuff” without returning anything (void) but very often they return something be it an Int, String, Array, etc.
In this case, what you have should work if you wrap the code inside a function. i.e.
function getImageSourceByDate() { // new open curly brace
var date = new Date();
.
.
.
else {
return 'image2.jpg';
}
} // new closing curly brace
While it’s not as easy for you personally, we tend to prefer helping people to understand why the problem is happening. That way you won’t need us to write your code over and over again afterwards.
That is simply NOT true. You have plenty of evidence of people trying to help you above (and in other posts). BUT, people are prepared to help you to learn, NOT do it for you.