In hmtl
file I have a simple button
<body>
<button type="button" onclick="create_button()">Create button</button>
</body>
and in js
file I have two functions
function create_button() {
var new_button = document.createElement("Button");
new_button.innerHTML = "Pop the alert";
new_button.type = "button";
new_button.onClick = my_function();
document.body.appendChild(new_button);
};
function my_function() {
alert("Not so fast");
};
Obviously it should work in following manner:
- Click Create button -> Pop the alert button appears
- Click Pop an alert -> "Not so fast" alert appers
However after I click Create button, the alert appears. I guess that Pop an alert button activates itsef, but I don't know how to prevent it from doing so.
Edit. I actually have a problem in which my_function
depends on some parameters.
So lets say we have following situation:
function my_function(x) {
alert("I like " + x);
};
and I want to create button which does my_function("Stack Overflow")
.
Based on this SO discussion I used
new_button.addEventListener('click', function(){my_function("Stack Overflow");});
and it works.