Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript click event handler fires without clicking

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);
}
like image 538
Mark Vonk Avatar asked Mar 27 '17 09:03

Mark Vonk


2 Answers

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");
});
like image 58
Suresh Atta Avatar answered Sep 27 '22 17:09

Suresh Atta


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);
}
like image 25
Devid Farinelli Avatar answered Sep 27 '22 18:09

Devid Farinelli