KarteMushroomPandas
KarteMushroomPandas

Reputation: 412

"OnClick" events created through JavaScript are triggering immediately, not when the object is clicked

Okay. We all know that we could do something like this:

<input type="button" value="Create Button" onclick="addB()"/>
<p id="demo"/>
<script>
function addB() {
var object1 = document.createElement("input");
object1.type="button";
object1.value="Example of value";
document.getElementById("demo").appendChild(object1);
}
</script>

Let's do that again, but modified a little bit. Now we'll add another function and give it another attribute.

<input type="button" value="Create Button" onclick="addB()"/>
<p id="demo"/>
<script>
function addB() {
var object1 = document.createElement("input");
object1.type="button";
object1.value="Example of value";
object1.onclick=myFunction();
document.getElementById("demo").appendChild(object1);
}

function myFunction() {
alert("You have clicked me.");
}
</script>

If you took the time to read the code, then what it's supposed to do is assign that button an onclick attribute so that when you click the generated button, it will trigger a function called "myFunction". But it doesn't do that. It calls the function immediately.

Does anyone know why this is happening or something I'm doing wrong? I would love some help. Thank you very much for your support.

Upvotes: 0

Views: 1323

Answers (2)

Mritunjay
Mritunjay

Reputation: 25892

You shouldn't be calling the function while assigning as attribute.

change following line

object1.onclick=myFunction();

to

object1.onclick=myFunction;

and it should work.

Upvotes: 2

Evan Knowles
Evan Knowles

Reputation: 7511

You're calling MyFunction, not assigning it as the event handler, because you're including the brackets. Change the line to

object1.onclick=myFunction;

Upvotes: 3

Related Questions