Javascript, Question about passing parameters into AddEventListener

Hello,

Thank you for reading this.

I am trying to work on a project and I’m hoping to figure out how to do a task.

There is a text box, that I want input a string value to. After doing this, I want to click a button and have that value be displayed on the console.log

The variable text, is suppose to save that value, it is linked to the element “textarea”

Basically I want to wring a string, such as my name, then click a button, which is the “button” element under addeventListener, and then console.log that value to the console itself. But I am having trouble getting that to work.

Any Assistance is greatly appreciated.



document.body.append(document.createElement('textarea'));

document.body.append(document.createElement('button'));

const text = document.querySelector('textarea').value;

const buttonClick = document.querySelector('button');

buttonClick.addEventListener('click', () => {
  console.log(text);
});


If you put the query selector into the callback function, you get the value at the time the button was clicked – not at the time when the textarea was initialized:

buttonClick.addEventListener('click', () => {
  console.log(document.querySelector('textarea').value);
});
2 Likes

Thank you so much, I always get the impression it’s something simple and I somehow still miss it :).

Is it possible to pass the variable itself ? Or is this the best method of use

The reason I ask is because the next part of the project require I pass multiple values into the box and do a few alterations to them. So I assumed the variable was needed for that.

1 Like

It’s better to declare the variable just once – in the outer scope – if you need it more often. This is also possible:

const textarea = document.querySelector('textarea')

const button = document.querySelector('button');

button.addEventListener('click', () => {
  console.log(textarea.value);
});
3 Likes

Thank you so much for your help. Your responses were able to help me get the ball rolling on the project :).

2 Likes

This is what I have often referred to as, node caching. It is my preferred approach, given that these important variables (objects) are exposed early.

1 Like