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);
    element.classList.remove("hidden-class");
    element.classList.add("show-class");
}

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.

markdown_Forums

Hi!

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(){
        test("test1");
      });

Hope you find it useful.

Martin.

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


function test(x)
{
    var element = document.getElementById(x);
     document.getElementById(x).classList.remove("hidden-class");
    element.classList.remove("hidden-class");
   
}
</script>

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:

2 Likes

Thanks! Glad it helped!