Reputation: 519
I am developing an app that stays in the website itself, and I want every link to call a function. I have tried this:
HTML
<a href="index.php">link</a><br>
<a href="news.php">link 2</a>
Javascript
var a = document.getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
a[i].onclick = function () {
return false
}
}
What is wrong? It doesn't work.
Upvotes: 0
Views: 479
Reputation: 5023
edit for pure javascript solution
document.addEventListener("click", function(e){
if (e.nodeName==="A"){
e.preventDefault();
return false;
}
}, false);
This will only add one single event to the document and prevent all clicks on anchor elements only.
I removed the old solution because of the comment, that this wasn't a jquery question
Upvotes: 1
Reputation: 2244
var a = document.getElementsByTagName("a").forEach(function (e) {
e.onclick = function (a) {
doSomething(a);
return false;
}
}
}
Upvotes: 0
Reputation: 3122
Don't use return false
, it does more than you really need. Instead try event.preventDefault()
Upvotes: 0
Reputation: 150313
Since it's not jQuery, you should use the preventDefault
function.
var a = document.getElementsByTagName("a");
for (var i = 0; i < a.length; i++) {
a[i].onclick = function (e) {
e.preventDefault();
doSomething();
}
}
Upvotes: 3