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.
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.
Share Improve this question edited Jun 5, 2021 at 8:40 Andrew 3077 silver badges13 bronze badges asked Jun 4, 2016 at 21:20 javajava 1,1652 gold badges29 silver badges52 bronze badges 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. – hipkiss Commented Jun 7, 2016 at 15:55
2 Answers
Reset to default 4a.onclick=myfunction()
Will set the return value of myfunction
as onclick. What you want is the following:
a.onclick=myfunction
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');
};