Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

121
Views
How to store previous event.currentTarget in a variable

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";
  }
})
7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.