Place the script after the a tag or wrap the script inside window.onload . Any of them 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 it doesn't work is because you bind to the click event of tag a before tag a ; therefore, he does not find any elements and will do nothing.
By placing the script inside window.onload , you tell the browser to run the script only after all the elements on the page are loaded and the element is found.
To prevent browser redirection to # , you can return false from your clicka function, as I noted above.
source share