Converting code

Work progresses on the convert jQuery to JavaScript challenge. Currently I’ve performed a basic conversion and applied some libraries so that modern techniques can be used on older web browsers. The queryselector polyfill coming from the Creating a querySelector for IE that runs at “native speed” as well as microAjax which allows an easy interface in which to obtain information without having to reload the page.

Fundamentally what the code is supposed to do is to act as tabs, where clicking on one tab loads content from an external page, and shows that content below the tab, without needing to reload the web page. jQuery is a JavaScript library that helps to simplify many aspects of web development. Here’s the jQuery code:

  $(".tab a").on("click", function(e){
    if ($(this).hasClass("selected")){
      return false;
    $(".tab a").removeClass("selected");
    var fileToLoad = $(this).attr("href");
    $("#content").fadeOut('slow', function(){


And here’s the JavaScript code, without any of the jQuery goodness.

I’ve broken out the code in to several functions with which to help aid the understandability of the code, and it’ll be interesting to see what changes come of it after working through some articles that express how to improve code in different ways than are currently known.

/*jslint browser: true */ /*globals microAjax */
(function () {
    'use strict';

    function addEvent(el, type, callback) {
        if (el.addEventListener) {
            el.addEventListener(type, callback, false);
        } else if (el.attachEvent) {
            el.attachEvent('on' + type, callback);

    function updateSelectedTab(tabLinks, currentLink) {
        var i;
        for (i = 0; i < tabLinks.length; i += 1) {

    function handleTabClick(link) {
        if (link.classList.contains('selected')) {
            return false;

        var tabLinks = document.querySelectorAll(".tab a"),
            fileToLoad = link.href;

        updateSelectedTab(tabLinks, link);
        microAjax(fileToLoad, function (response) {
            document.querySelector('#content').innerHTML = response;

    var tabLinks = document.querySelectorAll('.tab a'),
        tabClickHandler = function (evt) {
            evt = evt || window.event;

            if (evt.preventDefault) { // good with most web browsers
            } else { // for Internet Explorer
                evt.returnValue = false;

    for (i = 0; i < tabLinks.length; i += 1) {
        addEvent(tabLinks[i], 'click', tabClickHandler);

    handleTabClick(document.querySelector(".tab a"));