I'm new to JavaScript and I'm making a simple app that accomplishes the following:
- Stores objects within an array
- Creates un-ordered list using a for loop
- Background changes to color stored in array when corresponding list item is clicked
I completed #1 and 2, but am having trouble with 3. I reviewed the answer here below for assistance, but it didn't help solve the issue.
// function creating un-ordered list
// it works!
function makeUL(songTitle) {
var list = document.createElement('ul');
for (var i = 0; i < songTitle.length; i++) {
var track = songTitle[i];
var trackName = track.name;
var node = document.createElement("li");
node.appendChild(document.createTextNode(trackName));
list.appendChild(node);
}
return list;
}
document.getElementById('song-list').appendChild(makeUL(songTitle));
// here i call the list by tag name
var listItems = document.getElementById('song-list').getElementsByTagName('li');
// here's where it gets tricky
// the click works, but it always selects the last background-image in the array
for (var i = 0; i < listItems.length; i++) {
listItems[i].addEventListener("click", function changeBackground() {
document.body.style.background = "url(" + songTitle[i].background + ") no-repeat center center fixed";
document.body.style.backgroundSize = "cover";
})
}