Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  3] [ 6]  / answers: 1 / hits: 20002  / 10 Years ago, tue, august 12, 2014, 12:00:00

This may be a very dumb question, but I'm desperate right now. I'm trying to execute a javascript function by clicking on an anchor like this:



<head>
<script type=text/javascript>
function myFunction() {
alert('It was clicked');
}
Anchor.addEventListener('click', myFunction, false);
</script>
</head>

<a href=# id=Anchor>Click me</a>


But it's not working.



However, this works fine:



<a href=javascript:myFunction() id=Anchor>Click me</a>


And even this does:



<a href=# onclick=myFunction() id=Anchor>Click me</a>


What is the correct way to go? What am I doing wrong? A jsfiddle for example here.



Extra info:



I have set up other events using the same method, but somehow the anchor is the only one that doesn't work. Example:



<script type=text/javascript>
function aFunction() {
AnElement.style.display = 'none';
}
window.addEventListener('load', aFunction, false);
</script>


And the element is hidden perfectly fine when the window has finished loading.


More From » anchor

 Answers
21

The problem is that you were placing your script on HEAD section. Anchor doesn't exist by the time the script is executed and because of this you were getting Anchor is not defined.



Try this modified version that place the script after the html definition.



DEMO



<a href=# id=Anchor>Click me</a>
<script>
function myFunction() {
alert('It was clicked');
}
Anchor.addEventListener('click', myFunction, false);
</script>

[#69808] Sunday, August 10, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blaisep

Total Points: 748
Total Questions: 95
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
blaisep questions
Wed, Dec 16, 20, 00:00, 4 Years ago
Sun, Aug 16, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Mon, Nov 11, 19, 00:00, 5 Years ago
;