Trouble with changing my HTML onclicks into JS event listeners

Hi there.

I’m working on my twitch project and have been triggering all my buttons etc with the HTML onclick. I read that a lot of people don’t like mixing Javascript with HTML, so I’m trying to use addEventListener instead.

My problem is that previously I would have something like onclick = “fcc(this)”, but when I set up an event listener I don’t know how to pass the this argument through. I think I might have to use bind(), but I’m not really familiar with it and can’t get it working.

Here is my codepen.

An example of this in the tab div, which needs to pass through what tab is being pressed. Any advice would be appreciated.

I will show you how you can make the necessary changes for one of the event handlers and then you can use the same logic for the others. Below is your tab for Brad’s Streams:

<div class="tab" id="brad"><button><div class = "brad-inner-tab-div inner-tab-div">Brad's Streams</div></button></div>

First, you would remove the onclick=“brad(this)” from this code and then down in your JavaScript, you would have something like:

document.getElementById("brad").addEventListener("click", brad);

Then, in your brad function, you will need to add a single parameter. Based on how the addEventListener function works, an an “event” object gets returned and can be accessed via this parameter. So your brad function would become:

function brad(button) {
  getArrayStreams("brad", bradStreams);

While it would read better if the “button” parameter was named “event”, the “target” property contains the same value of this when you used the onclick=“brad(this)”.

1 Like

This worked perfectly! Thanks for taking the time to show this, much appreciated!