Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function to create buttons receiving "text" and "onclick function" by parameter

I want to do what I said in the title. I tried this:

function createButton(func, text){
    var butt = document.createElement('BUTTON');
    var btTxt = document.createTextNode(text);
    btTxt.style.color = '#006633';
    btTxt.style.fontWeight = 'bold';
    butt.onclick = func;
    butt.appendChild(btTxt);
    butt.style.margin = '5px';
    document.body.appendChild(butt);
}

And this:

createButton(doSomething, click to do something);

But it doesn't work :/

Anyone?

like image 833
razoes Avatar asked Dec 05 '25 10:12

razoes


1 Answers

You need to set styles of the button, not TextNode object:

function createButton(func, text) {
    var butt = document.createElement('BUTTON');
    var btTxt = document.createTextNode(text);
    butt.style.color = '#006633';
    butt.style.fontWeight = 'bold';
    butt.onclick = func;
    butt.appendChild(btTxt);
    butt.style.margin = '5px';
    document.body.appendChild(butt);
}

createButton(doSomething, 'click to do something');

function doSomething() { alert('Hello'); }
like image 140
dfsq Avatar answered Dec 07 '25 10:12

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!