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?
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?
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).
function linkClick(e) { alert(e.target.href); } links = document.getElementsByTagName('a'); for (i = 0; i < links.length; i++) links[i].addEventListener('click', linkClick, false);
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>
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);
});