Reputation: 9145
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.
Upvotes: 2
Views: 24960
Reputation: 5742
Just because you give the tag an id attribute like id="Anchor"
doesn't mean you can call it directly from javascript like you do: Anchor.addEventListener('click', myFunction, false);
You actually have to find the element before binding an event.
document.getElementById('Anchor').addEventListener('click', myFunction, false);
Upvotes: 4
Reputation: 1097
you shoul add your bind after pageload event, and use getElementById.
function myFunction() {
alert('It was clicked');
}
window.onload = function () {
document.getElementById('Anchor').addEventListener('click', myFunction, false);
}
Upvotes: 6
Reputation: 68410
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.
<a href="#" id="Anchor">Click me</a>
<script>
function myFunction() {
alert('It was clicked');
}
Anchor.addEventListener('click', myFunction, false);
</script>
Upvotes: 11