Adding Event Handlers

Link to exercise : Link

Question:

I’m trying to understand why the following code triggers early :

const textChange = function (e) {
  e.innerHTML = 'Hello, World!';
}

view.onclick = textChange(view);

Full code below:

// Add the code you want to test below:
let view = document.getElementById('view-button');
let close = document.getElementById('close-button');
let codey = document.getElementById('codey');

let open = function() {
  codey.style.display = 'block';
  close.style.display = 'block';
};

let hide = function() {
  codey.style.display = 'none';
  close.style.display = 'none';
};

view.onclick = open;
close.onclick = hide;

// Write your code here

const textChange = function (e) {
  e.innerHTML = 'Hello, World!';
}

view.onclick = textChange(view);

Hi!

Are you saying it changes to Hello, world before you click? What do you mean by early?

Yes as soon as the page loads.

view.onclick = textChange(view);

What happens if you remove this line?

I never wrote this line when I did this exercise but it’s kind of striking that it would trigger the event…

then the function can’t execute.

check out the blurb for the exercise again. they do mention another way…

i’ve also tried the .addEventListener(veiw) and i get it to work the way they wan’t it to. What i want to know is why the function can’t be made more general.

Coming from python/java, javascript always felt messy to me. I guess coming to terms with that is part of the battle.

1 Like

Found the solution. you need to use the .taget method.

const textChange = function (e) {
  e.target.innerHTML = 'Hello, World!';
}

view.onclick = textChange
1 Like

Good to see you’ve solved it. The reason that this didn’t work, I think,

view.onclick = textChange(view);

is because you’re not binding the textChange() function as an event handler here. Rather, you are calling textChange() and binding the result as the event handler.

Had you done view.onclick = textChange;, as you have done earlier in the exercise with view.onclick = open; you would not have prematurely triggered the execution of the textChange() function.

(What you would have done instead, though, is overwritten the event handler and replaced open() with textChange()… and so Codey would not appear when you click the button.)

1 Like