views:

160

answers:

4

Hello guys!

How can I get the href of an anchor when I click on it using javascript? I did the following:

function myFunc() {
}
window.onclick = myFunc;

But how to extend the function to respond only to clicks on anchors and get the href?

+1  A: 

Your document.onclick registers the handler on the whole document. But you should add it to every link. You can do this with JavaScript and using a framework like Prototype or jQuery makes it a lot easier:

$$('a').invoke('observe', 'click', function(a){
    myFunc(a);
});

But you can also use pure JS combining the getElementsByTagName function with a loop (see Delan's new answer).

Kau-Boy
It's really disappointing when you get down votes without any comment.
Kau-Boy
Your answer is good, but I need the solution without jQuery because jQuery is a bit overload for my issue. Thanks! :)
Infinity
It was a Prototype and not jQuery solution and I also pointed out how to do it without a framework. And you didn't tell use that you don't want use a framework or don't even have a framework in use.
Kau-Boy
+6  A: 
function linkClick(e) {
  alert(e.target.href);
}
links = document.getElementsByTagName('a');
for (i = 0; i < links.length; i++)
  links[i].addEventListener('click', linkClick, false);
Delan Azabani
This is what I need. Thanks!
Infinity
A: 
function myFunc(link) {
  alert(link.href);
  return false; // return false if you don't want to actually navigate to that link
}


<a href onclick="return myFunc(link)">something</a>
RoToRa
A: 

it won't work like this, you need to setup an onclick handler for every anchor. The easiest way to do this, is to use a javascript framework like jQuery or Prototype or something similar.

extend your function to recieve the calling object:

var myFunc = function(target) {
  var href = target.href;
  // ... your function code that can now see the href of the calling anchor
}

jQuery:

$('a').click(function(){
  myFunc(this);
});

Protype: see Kau-Boy's answer

jigfox
Your Prototype isn't correct. I posted exactly the same before. Have a look on my answers to see how to do that in Prototype.
Kau-Boy
thanks for the tipp
jigfox