I have to create a clown clothing changer website. Like a character selector in a video game. There are 3 parts, head, body, and shoes. Right and left keys cycle through the clothes, while the up and down keys change the selected part (head to body).
I have written my code and it cycles through the first part (head), but when I try to change to body or shoes, it doesn’t work. Please help me!
console.log("Dress The Clown!")
// Variables
let head = document.getElementById("head")
let body = document.getElementById("body")
let shoes = document.getElementById("shoes")
let headIndex = 0
let bodyIndex = 0
let shoesIndex = 0
let toggleIndex = 0
// Event for toggle (up and down keys)
document.addEventListener('keydown', (event) => {
console.log("toggleIndex is: " + toggleIndex)
console.log("headIndex is: " + headIndex)
console.log("bodyIndex is: " + bodyIndex)
console.log("shoesIndex is: " + shoesIndex)
if (event.key === "ArrowUp") {
toggleIndex++
} else if (event.key === "ArrowDown") {
toggleIndex--
}
if (toggleIndex < 0) {
toggleIndex = 2
} else if (toggleIndex > 2) {
toggleIndex = 0
}
})
// Event for head
if (toggleIndex === 0) {
document.addEventListener('keydown', (event) => {
if (event.key === "ArrowLeft") {
head.src = `./images/head${headIndex++}.png`
} else if (event.key === "ArrowRight") {
head.src = `./images/head${headIndex--}.png`
}
if (headIndex < 0) {
headIndex = 5
} else if (headIndex > 5) {
headIndex = 0
}
})
}
//Event for body
if (toggleIndex === 1) {
document.addEventListener('keydown', (event) => {
if (event.key === "ArrowLeft") {
body.src = `./images/body${bodyIndex++}.png`
} else if (event.key === "ArrowRight") {
body.src = `./images/body${bodyIndex--}.png`
}
if (bodyIndex < 0) {
bodyIndex = 5
} else if (bodyIndex > 5) {
bodyIndex = 0
}
})
}
// Event for shoes
if (toggleIndex === 2) {
document.addEventListener('keydown', (event) => {
if (event.key === "ArrowLeft") {
shoes.src = `./images/shoes${shoesIndex++}.png`
} else if (event.key === "ArrowRight") {
shoes.src = `./images/shoes${shoesIndex--}.png`
}
if (shoesIndex < 0) {
shoesIndex = 5
} else if (shoesIndex > 5) {
shoesIndex = 0
}
})
}