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?
Either place the script after the
atag or wrap the script insidewindow.onloadfunction. Either of these will work:Or:
The reason why it does not work is that you’re doing the binding to the
atag’s click event before theatag exists; hence it does not find any elements and will not do anything.By placing the script inside
window.onloadyou 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 canreturn falsefrom your clicka function, as I’ve marked above.