1

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.

Tristan Tran
  • 1,351
  • 1
  • 10
  • 36
  • 2
    addEventListener requires a function as the handler argument, not the result of calling a function - you could do `test_button.addEventListener('click', () => showText('test-button'))` – Jaromanda X Nov 04 '20 at 00:09
  • @JaromandaXI don't quite understand the difference. Could I trouble for you for more explanation or pointing to some documentation on JavaScript? I am a newbie in JS. – Tristan Tran Nov 04 '20 at 00:12
  • addEventListener function argument is only his name, as address, and this function must have only the event as argument – Mister Jojo Nov 04 '20 at 00:12
  • 3
    `fn()` calls a function ... `fn` does not – Jaromanda X Nov 04 '20 at 00:13

0 Answers0