I'm trying to write a switch statement that will dynamically change the background of my weather app project based on weather conditions, but my url relative paths are for some reason not being read properly in my JavaScript file despite working fine in CSS file.
switch (main) {
case "Clear":
document.getElementById("bgImage").style.backgroundImage = url(Images/clearskyday.gif);
break;
case "Clouds":
document.getElementById("bgImage").style.backgroundImage = url(Images/cloudsday.gif);
break;
case "Rain":
document.getElementById("bgImage").style.backgroundImage = url(Images/rainday.gif);
break;
case "Thunderstorm":
document.getElementById("bgImage").style.backgroundImage = url(Images/thunderstormday.jpg);
break;
case "Snow":
document.getElementById("bgImage").style.backgroundImage = url(Images/snow.gif);
break;
case "Default":
document.getElementById("bgImage").style.backgroundImage = url(Images/clearskyday.gif);
break;
};
For whatever reason the .gif portion of the image file isn't being read as part of the url itself despite being within the parenthesis of the url. Instead, it is being read as an "add on" such as .setattribute etc. I'm not sure why this is happening nor how to fix it. Any help is always appreciated!
CodePudding user response:
you should wrap the assignments in quotes. like:
document.getElementById("bgImage").style.backgroundImage = "url(Images/clearskyday.gif)";
I wonder why you don't get a reference error there.
also consider assigning the element into a const and: there is no case "Default". just use default.
const element = document.getElementById("bgImage");
switch(main){
case "Clear":
element.style.backgroundImage = "url(Images/clearskyday.gif)";
break;
... your other cases ...
default:
... your default case ...
}
CodePudding user response:
document.getElementById("bgImage").style.backgroundImage = url(Images/clearskyday.gif);
The URL should be a string here after compilation.
If Images is a folder name in the same directory, then the URL should be like
"url('./Images/clearskyday.gif')"
If Images is a variable containing the base URL of the images folder. Then your string should be like, any of these below
`url("${Images}/clearskyday.gif")`
or
`url("${Images} ${'/clearskyday.gif'}")`
Since you are using a bad URL format in your case. But why no syntax error? Because it is a valid URL format.
I hope this helps! Hola!