I am trying two ways to implement this situaiton: when a test-button
is clicked, a text Hello World
is displayed at <p>
element test-text
Method 1
function showText(test_button_id) {
let test_text = document.getElementById("test-text")
test_text.innerText = "Hello World";
}
let test_button = document.getElementById("test-button")
test_button.addEventListener('click', showText('test-button'))
Method 2
let test_button = document.getElementById("test-button")
let test_text = document.getElementById("test-text")
test_button.addEventListener('click', () => {
test_text.innerText = "Hello World";
})
Method 2 works. Method 1 does not. What is wrong with the way I am calling the function in addEventListener
? I know the argument test_button_id
is not doing anything in this code. I intend to parse it in if the code works. Thanks.