Mark Vonk
Mark Vonk

Reputation: 125

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);
}

Upvotes: 11

Views: 13828

Answers (3)

Devid Farinelli
Devid Farinelli

Reputation: 7554

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);
}

Upvotes: 3

stackoverflow
stackoverflow

Reputation: 1597

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

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122006

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");
});

Upvotes: 21

Related Questions