3

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.

1
  • I would definitely get in the habit of putting id's on the things you wish to manipulate. and just do something like "a.addEventListener('onclick', function(event){ do stuff here})". That would work. It wouldn't instantly execute - it would only execute "onclick" by having an event listener :). It's also possible to create custom event methods/listeners if required. Commented Jun 7, 2016 at 15:55

2 Answers 2

4
a.onclick=myfunction() 

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

a.onclick=myfunction 
Sign up to request clarification or add additional context in comments.

Comments

2

You can specify the onclick function in two ways:

1) with a named function:

function myFunction(){ alert('hello'); } a.onclick = myFunction; 

2) with an anonymous function:

a.onclick = function(){ alert('hello'); }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.