2
let btns = document.querySelectorAll("button");

function choosenOrder(chices1) {
  let btnsPair = [chices1[0], chices1[1]];
  btnsPair.forEach((choice) => {
    choice.addEventListener("click", (c1) => {
      let mychoice = c1.target.textContent;
      return mychoice;
    })
  })
}
console.log(choosenOrder(btns));

//return undefined

I will be simple and direct...

I want to return the text value of the button i press using the listener function inside addEventListener. However this is not working as expected, and what ever i try it either returns undefined or not work at all, is it even possible to return a value from an event listener?

If it is not, what kinda of alternatives do I have?

Thanks in advance!

2
  • 1
    Your outer function has no return statement. Only the inner callback has one. Also, you are looping before any button has pressed. All the collecting should be coded inside the event handler. Commented Aug 7, 2022 at 21:54
  • chosenOrder doesn't return anything. The function passed to addEventListener returns myChoice. Ultimately the function has to be asynchronous (and streamable, if not observable) in order to "return" a value from an event listener. Sounds like you need to rethink your design. Commented Aug 7, 2022 at 21:55

1 Answer 1

1

The return statement is inside the event handler, and cannot be taken into account by the wrapping function (when the handler is executed - asynchronously, the wrapping function call has already ended and returned). An alternative could be to use Promises. In the outer function, return the Promise, and inside the event listener, resolve that Promise with the value:

let btns = document.querySelectorAll("button");

function choosenOrder(chices1) {
  return new Promise(resolve => {
    let btnsPair = [chices1[0], chices1[1]];
    btnsPair.forEach((choice) => {
      choice.addEventListener("click", (c1) => {
        let mychoice = c1.target.textContent;
        resolve(mychoice);
      });
    });
  });
}

choosenOrder(btns).then(console.log);
<button>Choice A</button>
<button>Choice B</button>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.