Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set onclick handler to dynamically created button

I need to create button dynamically and assign its onclick handler. Click handler could be anonymous function (I'm not sure how it is called in JS). It is allowed to jQuery.
I tried something like this:

<div>
    <button id="x">Show</button>
</div>

function magick() {
    console.log('some special magick');
}

function createButton(itsHandler) {
    var guts = '<button id="__internal" onclick="' 
        + itsHandler +    // <-- that's wrong
        '">Test</button>';
    $($.trim(guts)).appendTo('body');
}

$(document).ready(function () {
    $("#x").bind("click", function() { 
            createButton(magick);
        });
});

but is doesn't work.

(Here is jsfiddled code)

How it can be accomplished?
UPD1: It would be better if it was done inside of the createButton function.

like image 438
Evgeny Timoshenko Avatar asked Sep 16 '25 11:09

Evgeny Timoshenko


1 Answers

Try to use on() like

$('body').on('click','#__internal',function(){
   console.log('test some special magick');
});

$(document).ready(function () {
    $("#x").bind("click", function() { 
       var guts = '<button id="__internal" >Test</button>';
       $($.trim(guts)).appendTo('body');
    });
}); 

Demo

Updated In your code, below two lines can create magic for you like,

var guts = '<button id="__internal">Test</button>';
$($.trim(guts)).appendTo('body').bind('click', magick);

Demo 1

like image 156
Rohan Kumar Avatar answered Sep 18 '25 02:09

Rohan Kumar