I am trying to store the previous node of the event.currentTarget in a variable to apply some styling to the previous node, and another to the current node but so far I haven't find a way.
Bellow you'll find the code I am trying to write but doesn't seem to store the variable as the previous target
questionsArray.map((question) => {
if (Object.values(question).includes(true) == true) {
let previousTarget = e.currentTarget
console.log(previousTarget)
e.previousTarget.className = "qgroup red";
e.currentTarget.className = "qgroup blue";
}
})
Calling a variable previousTarget
doesn't make it so. As is, this is just another name for the currentTarget
. Move previousTarget
outside the handler and only assign the currentTarget
to it at the very end of the handler.
previousTarget
will be undefined on first click, so be sure to handle that.
let prevTarget = null;
for (const div of [...document.querySelectorAll(".box")]) {
div.addEventListener("click", event => {
if (prevTarget) {
prevTarget.classList.remove("blue");
prevTarget.classList.add("red");
}
event.currentTarget.classList.add("blue");
prevTarget = event.currentTarget;
});
}
.box {
width: 50px;
height: 50px;
border: 1px solid black;
display: inline-block;
cursor: pointer;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
If you want the previous previous to be returned to the default state, you can do that too:
let prevTarget = null;
let prevPrevTarget = null;
for (const div of [...document.querySelectorAll(".box")]) {
div.addEventListener("click", event => {
if (prevPrevTarget) {
prevPrevTarget.classList.remove("red");
}
if (prevTarget) {
prevTarget.classList.remove("blue");
prevTarget.classList.add("red");
}
event.currentTarget.classList.add("blue");
prevPrevTarget = prevTarget;
prevTarget = event.currentTarget;
});
}
.box {
width: 50px;
height: 50px;
border: 1px solid black;
display: inline-block;
cursor: pointer;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>