0

Maybe an inappropriate question, but couldn't find a place to ask.

The problem: I have 3 numbers on html page (1.5, 2.5, -3.5). I want to select each of them with my mouse (double click), and get the result of calculation in a clipboard (in this example 0.5).

Is it possible to do?

Presto
  • 31
  • 2
  • 2
    There is an event for db click : https://developer.mozilla.org/fr/docs/Web/API/Element/dblclick_event If you put the numbers inside a dom element then you can attach a dbclick event to this element. There is also a Clipboard API : https://developer.mozilla.org/en-US/docs/Web/API/Clipboard – A.DUPONCHEL Jul 16 '21 at 11:03

1 Answers1

0

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!

Very cool
  • 148
  • 7