Hi Campers,
While building a weather app I have run into an issue with a click listener I am trying to make. In a loop I am creating elements and filling them with data. I also want to make it so I can click on these elements and trigger a function. What happens instead is that when I press the button that initiates the loop to create these elements, that button is instead triggering the click listener, once for each iteration of the loop. I can not then click on my created elements to trigger the click listener. I tried putting the addEventListener in other places, but it seems to keep being associated with my search button element instead of the “more details” divs I am creating.
let dayDivDetails = document.getElementById(`dayDivDetails${i+1}`)
dayDivDetails.addEventListener("click", console.log("hi"))
Here is the full loop:
//fill the divs with weather info
for(let i=0; i<5; i++){
//days and dates
document.getElementById(`dayDivDate${i+1}`).innerHTML = parseApiInfo(weatherData).dates[i]
document.getElementById(`dayDivDay${i+1}`).innerHTML = parseApiInfo(weatherData).weekdays[i]
document.getElementById(`dayDivDesc${i+1}`).innerHTML = parseApiInfo(weatherData).descriptions[i]
document.getElementById(`dayDivImg${i+1}`).src = `http://openweathermap.org/img/w/${parseApiInfo(weatherData).icons[i]}.png`
let dayDivDetails = document.getElementById(`dayDivDetails${i+1}`)
dayDivDetails.innerHTML = "See Hourly"
dayDivDetails.className += "dayDivDetails"
//make it so you can click on a day for more info
dayDivDetails.addEventListener("click", console.log("hi"))
// createHourDivs(weatherData, parseApiInfo(weatherData).datesOriginal[i])
//high and low temps
let fTempMin = Math.round(1.8*(tempMinMax(weatherData).minTemps[i]-273) + 32)
let fTempMax = Math.round(1.8*(tempMinMax(weatherData).maxTemps[i]-273) + 32)
document.getElementById(`dayDivTemp${i+1}`).innerHTML = `${fTempMax}° F / ${fTempMin}° F`
}
The full repo: