2

If writing the event inline (onclick) it works fine. But with addEventListener the event is triggered on page load. I would like to understand why.

const boxDiv = document.getElementsByClassName("childbox")[0];
boxDiv.addEventListener("click", respondToClick (event));
    
function respondToClick (event) {
    alert("clicked")
                }
.parentbox {
    width:900px;
    height:70px;
    display:flex;
    justify-content:center;
    align-items:center;
    background-color:#06283D;
    border: solid 6px black;
}

.childbox {
 display:flex;
 justify-content:center;
 align-items:center;
 height:60px;
 width:60px;
 font-family:'Lato', sans-serif;
 text-align:center;
 background-color:steelblue;
 border:3px solid black;
 border-radius:50%;
}
<div class="parentbox">
<div class="childbox">
    <div class="text">
    <p>Wait! </p>
    </div>
</div>
</div>
olbapnairda
  • 35
  • 11
  • `respondToClick (event)` runs the function immediately - you want `boxDiv.addEventListener("click", respondToClick)` – Bravo Jun 08 '22 at 05:34

2 Answers2

2

The parenteses after respondToClick are calling the function immediately.

You either need to remove the parenteses or wrap the function in another function:

boxDiv.addEventListener("click", (event) => respondToClick(event));
boxDiv.addEventListener("click", respondToClick);

Regarding the second option, you don't see the event, but that is being passed in automatically. It's just a cleaner way to write it. You need the first option when you want to pass in additional arguments: (event) => respondToClick(event, myAdditionalArgs))

Mads Akselsen
  • 249
  • 1
  • 5
1

In your code, you trigger/call a function instead of registering it as a callback.

The correct one should be

const boxDiv = document.getElementsByClassName("childbox")[0];
boxDiv.addEventListener("click", function (event) { respondToClick(event) }); // Or just boxDiv.addEventListener("click", respondToClick);
    
function respondToClick (event) {
    alert("clicked")
}
Quoc-Anh Nguyen
  • 4,798
  • 1
  • 22
  • 34
  • 1
    The declaration you mentioned in a comment should be your primary answer cause writing an anonymous function and then declaring another function in it just for the sole purpose is redundant either you can write the whole function anonymously or with commented declaration. – Abbas Shaikh Jun 08 '22 at 05:44
  • Thanks, now I understand it well after a brief review of callback functions. In this video she explains it in a similar context using addEventListener in case someone with the same issue reads here. https://www.youtube.com/watch?v=cNjIUSDnb9k – olbapnairda Jun 08 '22 at 06:11