Javascript onclick in script
hyperlink, javascript, onclick
Solution
Either place the script after the `a` tag or wrap the script inside `window.onload` function. Either of these will work:
<script type="text/javascript">
window.onload = function() {
function clicka() {
alert("hi");
return false;
}
document.getElementById('click').onclick = clicka;
}
</script>
<a href="#" id="click">click</a>
Or:
<a href="#" id="click">click</a>
<script type="text/javascript">
function clicka() {
alert("hi");
return false;
}
document.getElementById('click').onclick = clicka;
</script>
The reason why it does not work is that you're doing the binding to the `a` tag's click event before the `a` tag exists; hence it does not find any elements and will not do anything.
By placing the script inside `window.onload` you instruct the browser to run the script only after all elements in the page are loaded and the element can be found.
To prevent the browser from actually redirecting to `#`, you can `return false` from your clicka function, as I've marked above.
Problem
Ok im new to javascript, but I want to call an onclick function without adding onclick="function()" to the anchor tag. Here is the script I have, but I cant get it to work: ``` <script type="text/javascript"> function clicka() { alert("hi"); } document.getElementById('click').onclick = clicka; </script> <a href="#" id="click">click</a> ``` When I click on the link, it should alert "hi", any ideas?