John
John

Reputation: 139

AppendChild Link with onClick function

I'm trying to use appendChild within Javascript to create a link that has a onClick attribute. I can't seem to make it work or find how to do this simple task.

var link=document.createElement("a");
link.appendChild(document.createTextNode("Link"));
link.href = '#';
link.onclick = 'loadScript()';
document.body.appendChild(link);

Upvotes: 2

Views: 17234

Answers (3)

Ana Mejía
Ana Mejía

Reputation: 1

To prevent the function from running when declaring the call, the following worked for me:

link.onclick = function(){
    return loadScript()
}

Without problems you can send the variables you need to loadScript function.

Upvotes: 0

Maral Azizi
Maral Azizi

Reputation: 21

Try this:

window.onload = function () {
  var files = document.getElementById('files');
  document.getElementById('addLink').onclick = function () {
    var file = document.createElement('input');
    file.type = 'file';
    files.appendChild(file);
  };
};

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68400

You have to change

link.onclick = 'loadScript()';

by

link.onclick = loadScript;

DEMO

Upvotes: 10

Related Questions