Fikre
Fikre

Reputation: 565

Adding event handler (with parameters) to element created using document.createElement

In the function below I'm trying to create a dynamic element (textArea). I'm trying to bind a function (resize) to the text area using textArea.onclick = resize; which works fine.

What I'd like to do is pass a parameter to the resize function (either the generated id or, if possible, the textArea itself)

    function addElement(elm, event) {
        var textArea = document.createElement('textarea');
        var id = Math.random();
        textArea.setAttribute('id', id)
        textArea.setAttribute('cols', 1);
        textArea.setAttribute('rows', 3);
        textArea.onclick = resize;
        elm.appendChild(textArea);
    }

if I say textArea.onclick = resize(id); then that just calls the function.

How can i bind the function, and pass a parameter to it?

Upvotes: 5

Views: 12955

Answers (3)

naikus
naikus

Reputation: 24472

You can create a function called resize from another function.

     function addElement(elm, event) {
        var textArea = document.createElement('textarea');
        var id = Math.random();
        textArea.setAttribute('id', id)
        textArea.setAttribute('cols', 1);
        textArea.setAttribute('rows', 3);
        textArea.onclick = createResizeFunction(textArea); // assign resize 
                                                           //function 
        elm.appendChild(textArea);
     }

     function createResizeFunction(textArea)  {
        var resize = function() {
           var id = textArea.id;
           // do something with that id
        };
        return resize;
     }

Upvotes: 1

Anurag
Anurag

Reputation: 141909

You can access the id, and the textarea from the event object itself. In the resize function, access the textarea, and subsequently the id as:

function resize(event) {
    var textarea = event.target;
    var id = textarea.id;
}

Upvotes: 1

MooGoo
MooGoo

Reputation: 48280

Use a closure:

textArea.onclick = function() { resize(id); };

Or use the elements id attribute:

textArea.onclick = function() { resize(this.id); };

Upvotes: 10

Related Questions