11

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
  • 9,608
  • 6
  • 34
  • 56
Mark Vonk
  • 125
  • 1
  • 1
  • 7

3 Answers3

21

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,514
  • 9
  • 42
  • 73
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 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
3

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,514
  • 9
  • 42
  • 73
0
document.getElementById("main_btn").addEventListener("click", hideId.bind(null, "main");
Devid Farinelli
  • 7,514
  • 9
  • 42
  • 73
stackoverflow
  • 1,303
  • 2
  • 21
  • 36
  • 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