Functions and parameters

I have a problem because all test(parameter) are working just when a page loads and not when I click on the buttons. I’m trying to make it that when I click on the button function will work with parameter from addEventListener.

My current code:

document.getElementById("1").addEventListener("click", test("test1"));
document.getElementById("2").addEventListener("click", test("test2"));
document.getElementById("3").addEventListener("click", test("test3"));
document.getElementById("4").addEventListener("click", test("test4"));

function test(x)
     var element = document.getElementById(x);

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.



The problem is that in JavaScript the line “test()” invokes the function test. The solution is write your handlers this way:

document.getElementById("1").addEventListener("click", function(){

Hope you find it useful.


1 Like
<div id="test1" class="hidden-class">
    Hello Cruel World
    document.getElementById("1").addEventListener("click", test("test1"));

function test(x)
    var element = document.getElementById(x);

Yeah I tested it several times document.Getelementbyid…etx
runs the code automatically in ur case withour even have to click the button.
Martin u deserve a like :grinning:


Thanks! Glad it helped!