I am making a weather like app. the JS file i use, has a script that makes the background image change to whatever the condition is, Now the issue is; that the image URL is wrong. I’ve tried anything possible, it stays on url(“../img/((condition name)).jpg”) (the (( and )) were made by me for a example) instead of url(“../website/assets/img/((condition name)).jpg”)
The code:
JS:
const updateWeatherFrame = (city) => {
if (!city) {
console.error("No city provided for weather update.");
return;
}
const weatherApiUrl = `https://api.weatherapi.com/v1/current.json? key=${process.env.WEATHER_API_KEY}&q=${city}&aqi=yes`;
fetch(weatherApiUrl)
.then((response) => {
if (!response.ok) {
throw new Error("Failed to fetch weather data");
}
return response.json();
})
.then((data) => {
const currentCondition = data.current.condition.text;
let backgroundImage = "url('./assets/img/default.jpg')";
for (const entry of conditionToImageMapping) {
if (entry.conditions.includes(currentCondition)) {
backgroundImage = `url('./assets/img/${entry.image}')`;
break;
}
}
const weatherFrame = document.getElementById("weatherframe");
if (weatherFrame) {
weatherFrame.style.backgroundImage = backgroundImage;
}
})
.catch((error) => {
console.error("Error fetching weather data:", error);
});
};
document.addEventListener("DOMContentLoaded", () => {
updateWeatherFrame("New York"); // Example city for initial update
setInterval(() => updateWeatherFrame("New York"), 300000); // Update every 5 minutes
});
CSS:
.weatherfr {
width: 100%;
height: 500px;
background-color: lightblue;
background-size: cover;
/* Ensures the image covers the entire DIV */
background-position: center;
/* Centers the image */
background-repeat: no-repeat;
/* Prevents image repetition */
transition: background 0.5s ease;
/* Smooth transition */
}
HTML:
<div id="weatherframe" class="weatherfr">
</div>
<!-- Link to the JavaScript file -->
<script src="../website/assets/js/weather.js"></script>
I tried to set the background image of the div to the image, yet only the background image displays. I expected it to have the path i mentioned above.