Infinite Possibilities
Infinite Possibilities

Reputation: 7466

JavaScript get anchor href on click

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?

Upvotes: 4

Views: 17397

Answers (4)

jigfox
jigfox

Reputation: 18185

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

Upvotes: 1

2ndkauboy
2ndkauboy

Reputation: 9377

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).

Upvotes: 2

RoToRa
RoToRa

Reputation: 38400

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>

Upvotes: -1

Delan Azabani
Delan Azabani

Reputation: 81384

function linkClick(e) {
  alert(e.target.href);
}
links = document.getElementsByTagName('a');
for (i = 0; i < links.length; i++)
  links[i].addEventListener('click', linkClick, false);

Upvotes: 13

Related Questions