Robin Timman
Robin Timman

Reputation: 519

Javascript every href onclick

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

Answers (4)

japrescott
japrescott

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

howderek
howderek

Reputation: 2244

var a = document.getElementsByTagName("a").forEach(function (e) {
       e.onclick = function (a) {
           doSomething(a);
           return false;
       }
    }
}

Upvotes: 0

Andrei Nemes
Andrei Nemes

Reputation: 3122

Don't use return false, it does more than you really need. Instead try event.preventDefault()

Upvotes: 0

gdoron
gdoron

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

Related Questions