Functions and parameters

Functions and parameters
0.0 0

#1

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

#2

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.


#3

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.


#4
<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:


#5

Thanks! Glad it helped!