views:

608

answers:

3

Hi there,

Can anyone help, seem to have an issue placing a onclick event of an anchor tag, it works on an image.. I have this

this.whereAreWe = document.getElementById('where_are_we');
this.whereAreWe.onclick = this.whereAreWe;

I have placed a A tag using the id of "where_are_we" ...

but it never executes.. if I change it to an image it works..

I also put the href="#"

Is there something special about anchor tags and applying the onclick via code?

I also tried removing the href, If I remove the href it doesn't show me the little hand icon.

I have put a breakpoint in the function and with an image it enters but using the anchor it doesn't

Any ideas?

+2  A: 

The code you provided is confusing. The following code works correctly for me:

<a href="#" id="whereWeAre">a link</a>
<script type="text/javascript">
  var whereWeAre = document.getElementById("whereWeAre");

  function testClick() {
    alert("You clicked!");
  }

  whereWeAre.onclick = testClick;
</script>

If your example was a little more specific we could probably be more helpful.

Zack Mulgrew
+1  A: 

The are 2 problems with your javascript. The use of the "this" and the binding of the onclick event back to the reference of the DOM element for the HREF. Try this instead:

var whereAreWe = document.getElementById("where_are_we");
whereAreWe.onclick = function(){ 
     alert("Click event on Where are We");
     return false;
};
Jose Basilio
A: 

I also tried removing the href, If i remove the href it doesn't show me the little hand icon.

You need the 'href' attribute for the 'a' tag in order to specify the URL of the destination document or web resource. In case you do not specify it - mouseover doesn't change the cursor. Of course you could use CSS to modify that but that is a different question.

dalizard