Yes, it is definitely possible.
When the numbers are clicked, which are <button>
in my example, it will add the class selected
to the button clicked, to indicate that the number is selected, or remove it depending on the presence of the class selected
.
After updating the class, it will call the function calculateSum()
, which will select all the elements with the class selected
and add the innerText
, which are the selected numbers in this case, of them together.
Lastly, the result
will be passed to the function renderUpdate()
to visualize the updates.
const selectableNumbers = document.querySelectorAll('.numbers')
selectableNumbers.forEach(n => {
n.addEventListener('dblclick', e => {
if (n.classList.contains('selected')) {
n.classList.remove('selected')
} else {
n.classList.add('selected')
}
calculateSum()
})
})
function calculateSum() {
let result = 0
const selectedNumbers = document.querySelectorAll('.selected')
selectedNumbers.forEach(n => {
result += parseFloat(n.innerText)
})
renderUpdate(result)
}
function renderUpdate(result) {
const resultOutput = document.querySelector('.spanResult')
resultOutput.innerText = `Sum: ${result.toString()}`
}
.selected {
background-color: grey;
color: white;
}
<button class="numbers">1.5</button>
<button class="numbers">2.5</button>
<button class="numbers">-3.5</button>
<span class="spanResult">Sum: 0</span>
For clipboard: https://stackoverflow.com/a/30810322/16491678
Hope this helps!