I am trying to create an app where each click of a button will create a new stopwatch, which consist of an h1 and a div element:
const addButton = document.querySelector('.add-button')!;
addButton.addEventListener('click', createTimer);
function createTimer() {
var divTimer = document.createElement('div');
var divHeader = document.createElement('h1');
divHeader.textContent = 'Timer';
divTimer.textContent = '00:00:00';
document.body.appendChild(divHeader);
document.body.appendChild(divTimer);
}
However, I want to associate each stopwatch's DOM elements created from the button press above, with a stopwatch object. The idea is that each stopwatch should have its own seconds, minutes, hours.
const testTimerDisplay = document.getElementById('timerA')!;
//Class based objects ES6
class Stopwatch {
seconds: number;
minutes: number;
hours: number;
constructor() {
this.seconds = 0;
this.minutes = 0;
this.hours = 0;
}
tick() {
setInterval(() => {
this.seconds++
testTimerDisplay.textContent = this.seconds.toString(); //NOT A GOOD IMPLEMENTATION
}, 1000)
}
}
const timerA = new Timer();
As you can see, when I call tick(), it'll only modify testTimerDisplay which of course is not what I ultimately want. Is there a way for me to click the button and associate a new stopwatch object with the DOM that it creates?