views:

75

answers:

5

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?

+6  A: 

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
Mic
because the script tag doesn't know the a tag exists until it's reached it.
CrazyJugglerDrummer
+3  A: 

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.

Tatu Ulmanen
A: 

if the function is before the tag, the document.getElementById('click') returns null. So put it after the tag and it will work.

Giovanni Di Milia
+1  A: 

Your script is running before the page has completely loaded. So document.getElementById('click') returns nothing. If you want to keep your script at the top, you need to add an onload event to the body:

<script type="text/javascript">

function clicka() {
 alert("hi");
}

function init() {
 document.getElementById('click').onclick = clicka;
}

</script>

<body onload="init()">

  <a href="#" id="click">click</a>

</body>

Or you can use window.onload

<script type="text/javascript">

function clicka() {
 alert("hi");
}

function init() {
 document.getElementById('click').onclick = clicka;
}

window.onload = init;

</script>


<a href="#" id="click">click</a>    
Vivin Paliath
-1 Showing the `onload="init()"` example isn't necessary and is devaluing since the OP already stated that he's trying to stay away from such things. Also, and more importantly, `window.onload = init;` fails since `init` is not yet defined.
Justin Johnson
Good catch - I should have put that window.onload = init; after the function definition.
Vivin Paliath
+1  A: 

Tatu Ulmanen's solution is correct, but it's worth discussing why. Here's a sort of quick-and-dirty explanation of what happens when a page is loaded

JavaScript and the DOM are two different things. In short, the DOM is a hierarchical data structure that represents the HTML page from which an API is exposed to JavaScript via objects like document and others.

The DOM can be thought of as an unbalanced tree with an arbitrary (not fixed) amount of nodes at any level. When a page is loaded, each node/element/tag is evaluated and attached to the DOM tree in the order that it is encountered. When a script element is encountered, it is full evaluated and executed before evaluating the rest of the HTML document.

Since your script node is before the a node that it is referencing, the a node does not yet exist in the DOM tree, which is what is causing your issue. By moving the script element after the nodes that is referencing (typically at the bottom of the page before the closing body tag), these types of errors are avoided. Another common practice is to use the DOM's onload event; this defers the execution of whatever function is assigned as its handler till the entire HTML page has been parsed/rendered into the DOM tree. The later method also allows you to include your script anywhere in the page you'd like (e.g.: in the head).

Justin Johnson