Search code examples
javascripthtmlonclickhref

Dynamically create onclick event anchor element - Javascript


How do I dynamically create a onclick function in a hyperlink in JavaScript?

This is a code snippet - a while loop that creates several hyperlinks within the same page. I tried to just add the onclick event to the a-element, that is:

a.onclick=myfunction()

However, when the page is loaded with a list of these links, the function is automatically called for every link.

This is how my code looks like. I guess I should use an id for every link?

  var a = document.createElement('a');
  var linkText = document.createTextNode(child.innerHTML);
  a.appendChild(linkText);
  a.title = child.innerHTML;
  a.href = "#stockContent" + i;
  a.id = "link_id" + i;

  ...

"i" is the iterator variable.


Solution

  • a.onclick=myfunction()
    

    Will set the return value of myfunction as onclick. What you want is the following:

    a.onclick=myfunction