Reputation: 741
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:
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.
Upvotes: 1
Views: 134
Reputation: 5953
You can use new_button.addEventListener('click',my_function);
.
So my_function
would be referenced, but not called imidiatley:
function create_button() {
var new_button = document.createElement("Button");
new_button.innerHTML = "Pop the alert";
new_button.type = "button";
new_button.addEventListener('click', my_function);
document.body.appendChild(new_button);
};
function my_function() {
alert("Not so fast");
};
<button type="button" onclick="create_button()">Create button</button>
After the edit
If your my_function
have arguments
, you have to wrap it into anonymous function
, so it would be:
new_button.addEventListener('click',function(){
my_function(5);
});
Or
new_button.onclick=function(){
my_function(5);};
Upvotes: 2
Reputation: 1057
As extend to @itsgoingdown answer:
function create_button() {
var new_button = document.createElement("Button");
new_button.innerHTML = "Pop the alert";
new_button.type = "button";
new_button.addEventListener('click', function () {
var x = ' sport'
my_function(x)
});
document.body.appendChild(new_button);
};
function my_function(x) {
alert("Not so fast" + x);
};
Upvotes: 2