Hello I am trying to make a simple project where the program tracks and records the details of the click
events from the targets
that fires the events in trackObject
, and then stores it in the details
array.
However, it keeps updating the previous trackObject
with every new click that I make. For example, when I click Box 1
, it stores the details of the events from Box 1
into details
, but when I click Box 2
, it stores also the details from Box 2
, but also replaces the details of Box 1
. In the end, details of Box 2
are stored twice in details
array.
May I please know what my mistake is here?
Thank you!
<html>
<body>
<div class="container">
<div id="box1" class="box">Box 1</div> <br>
<div id="box2" class="box">Box 2</div> <br>
<div id="box3" class="box">Box 3</div> <br>
<div id="box4" class="box">Box 4</div> <br>
</div>
<script>
let container = document.querySelector(".container");
let details = [];
let trackObject = {
textContent: null,
id: null,
tagName: null,
className: null
}
container.addEventListener("click", function (e) {
trackObject.textContent = e.target.textContent;
trackObject.id = e.target.id;
trackObject.tagName = e.target.tagName;
trackObject.className = e.target.className;
details.push(trackObject);
console.log(details);
})
</script>
</body>
</html>
let container = document.querySelector(".container");
let details = [];
let trackObject = {
textContent: null,
id: null,
tagName: null,
className: null
}
container.addEventListener("click", function(e) {
trackObject.textContent = e.target.textContent;
trackObject.id = e.target.id;
trackObject.tagName = e.target.tagName;
trackObject.className = e.target.className;
details.push(trackObject);
console.log(details);
})
<div class="container">
<div id="box1" class="box">Box 1</div> <br>
<div id="box2" class="box">Box 2</div> <br>
<div id="box3" class="box">Box 3</div> <br>
<div id="box4" class="box">Box 4</div> <br>
</div>