9

Why does this function get fired without having clicked on the specified button? I had a look at a few similar problems but none deal with this code structure (might be obvious reason for this im missing...).

document.getElementById("main_btn").addEventListener("click", hideId("main");

function hideId(data) {
    document.getElementById(data).style.display = "none";
    console.log("hidden element #"+data);
}
Ronan Boiteau
  • 8,910
  • 6
  • 33
  • 52
Mark Vonk
  • 105
  • 1
  • 6

3 Answers3

18

You are directly calling it.

document.getElementById("main_btn").addEventListener("click", hideId("main");

You should do that in a callback.

document.getElementById("main_btn").addEventListener("click", function (){
    hideId("main");
});
Devid Farinelli
  • 7,329
  • 8
  • 38
  • 71
Suresh Atta
  • 118,038
  • 37
  • 189
  • 297
  • This worked, thank you! It all makes sense now, I saw this solution come by a few times but I didn't understand why you had to call the function within another function. But I guess you're telling the event handler to execute the function after clicking instead of just putting it there to execute by itself. – Mark Vonk Mar 27 '17 at 09:48
2

This code executes your function hideId("main") you should pass just the callback's name:

document.getElementById("main_btn").addEventListener("click", hideId);

function hideId(event) {
    var id = event.target.srcElement.id; // get the id of the clicked element
    document.getElementById(data).style.display = "none";
    console.log("hidden element #"+data);
}
Devid Farinelli
  • 7,329
  • 8
  • 38
  • 71
0
document.getElementById("main_btn").addEventListener("click", hideId.bind(null, "main");
Devid Farinelli
  • 7,329
  • 8
  • 38
  • 71
stackoverflow
  • 715
  • 1
  • 17
  • 31
  • 4
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Donald Duck Mar 27 '17 at 11:24