Search code examples
javascriptdomscopecalculator

How can I store the e.target.innerText from 'button' tag when is pressed?


i'm in calculator project and i'm in part 5. "Create the functions that populate the display when you click the number buttons. You should be storing the ‘display value’ in a variable somewhere for use in the next step." and I'm having troubles storing the value of the button pressed by the user to use later as operands and operators. github repository

Now, i'm trying to get and store in some var the innerText from the clicked buttons to use as input values from the user. To do this, I chosed to use a listener inside a forEach, but at the moment only I could return the innerText to the console. Also I tried to encapsulate the following code inside a function but by scope function limitations I couldn't return the innerText through the function. Example of what I tried:

const buttons = document.querySelectorAll(".buttons-grid")
function getInner(){
buttons.forEach((button) =>{
  button.addEventListener('click', e => {
    return console.log(e.target.innerText)
  })
})
return e.target.innerText //doesn't work
} 

Going on, what I need, is to think in one or two ways to store the value of the key pressed by the user, to use later as operands or operators.

Also I would like to give in knowledge that I miss some important concepts to understand what i'm doing and what I have to do, so for that, I will give thanks for any kind of illustration about it as learning resources too.

What i'm doing:

const buttons = document.querySelectorAll(".buttons-grid")

buttons.forEach((button) =>{
  button.addEventListener('click', e => {
    return console.log(e.target.innerText)
  })
})

Solution

  • You can use a variable outside of the event listener function and assign it the value of e.target.innerText when a button is clicked:

    const buttons = document.querySelectorAll(".buttons-grid");
    let displayValue = '';
    
    buttons.forEach((button) => {
      button.addEventListener('click', e => {
        displayValue = e.target.innerText;
        console.log(displayValue);
        // do something with the displayValue variable
      })
    

    });