Search code examples
javascriptajaxpreventdefault

Javascript code to preventDefault for all <a href> links


I am trying to get URLs to change using only Javascript, by updating the content via AJAX.

This is to prevent certain content (namely music, chat message boxes, etc) from refreshing and either

  1. Clearing the place where your music is playing
  2. Resetting something you are working on, like typing a message.

I just began today trying to implement something like this, and so far I've got this:

var a = document.querySelectorAll('a')
for (var i=0; i<a.length; i++) {
   a[i].addEventListener('click',function(event){event.preventDefault();};
}
return false

However, this code

  1. Doesn't allow the url to be changed
  2. Doesn't load the AJAX.

My question is: how do I cancel the age from refreshing, but still allow the url to change?


Solution

  • Try something like

    var a = document.getElementsByTagName('a'),
        ajax;
    for (var i=0; i<a.length; ++i) {
       a[i].addEventListener('click', handleAnchor, false);
    }
    function handleAnchor(e){
        e.preventDefault();
        if(ajax) ajax.abort();
        ajax = new XMLHttpRequest();
        ajax.onload = updateContent;
        ajax.open("get", this.href, true);
        ajax.send();
    }
    function updateContent() {
        // Do something with `this.responseText`
    }