Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript onclick in script

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?

like image 954
john Avatar asked Dec 06 '22 03:12

john


2 Answers

Place the SCRIPT tag after the A tag. The browser parse the tags sequentially, and the A does not exist yet when the SCRIPT tag is parsed.

Some other comments too:

  • You can dump the type="text/javascript"
  • You can set href="javascript:void(0)" to avoid polluting the hash key when you click
  • Or you return false; in your onclick function
like image 177
Mic Avatar answered Dec 09 '22 15:12

Mic


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.

like image 28
Tatu Ulmanen Avatar answered Dec 09 '22 14:12

Tatu Ulmanen