Javascript Sans JPath

Lately I’ve been delving a lot more into modern JS frameworks like JQuery, MooTools, and Prototype. Coming from a procedural programming background the emphasis on anonymous functions, chaining, and some other things takes some getting used-to. Reminds me of Lisp, Python, or even Prolog (no not really). For kicks I decided to dig up an old-school pure Javascript piece of code that began as some samples I adapted from other pages around 2004 or so, and improve upon it – add a preloader, more event handling, etc,.. Sans XPath, here is what I came up with:

// can be set by back-end
var num_of_slides = 35;
// horrifying C-style globals
var slide_num = 0; // start at the beginning
var desc = new Array(num_of_slides);    // optional per image
var pics = new Array(num_of_slides);    // file paths
var imgs = new Array(num_of_slides);    // the actual image data
var auto = 0;   // auto-advance? this could be boolean
var interval;   // ms between slide in auto-mode
var tID = null; // timeout between slides in auto-mode
var load_cnt = 0;   // number of images that have been pre-loaded
var lID = null; // timeout for preloading all images

// most of the following are self-explanatory
function setInterval(i) {
    interval = i;
}
function closeWindow() {
    window.close();
}
// following functions ignore requests if in auto-mode
function firstSlide() {
    if (!auto) {
        slide_num = 0;
        changeSlide();
    }
}
function prevSlide() {
    if (!auto) {
        slide_num = slide_num - 1;
        if (slide_num < 0) {
            slide_num = 0;
        }
        changeSlide();
    }
}
// only function that needs to differentiate between user/auto request
function nextSlide(called_by) {
    if (slide_num == num_of_slides - 1) { // if on last slide turn off auto
        auto = 0;
        document.getElementById('autoOn').checked = false;
    } else {
        if ((auto) && (called_by == "usr")) {
            return;
        }
        slide_num = slide_num + 1;
        changeSlide();
        if (auto) {
            tID = setTimeout('nextSlide(auto)', interval);
        }
    }
}
function lastSlide() {
    if (!auto) {
        slide_num = num_of_slides - 1;
        changeSlide();
    }
}
function changeSlide() {
    // following may not need to be evals
    eval('document.picbox.src = pics[slide_num]');
    eval('document.descform.descbox.value = desc[slide_num]');
}
function toggleAuto() {
    if (document.getElementById('autoOn').checked == true) {
        auto = 1;
        tID = setTimeout('nextSlide(auto)', interval);
    } else {
        clearTimeout(tID);
        auto = 0;
    }
}
// called when either all images are preloaded, or the preload timeout has fired
function slidesReady() {
    clearTimeout(lID);
    lID = null;
    // swap "still-loading" content for slideshow content
    document.getElementById('content').style.display = 'block';
    document.getElementById('loading').style.display = 'none';
}
function isLoaded() {
    // keep track of how many images preloaded and stop when done
    if (++load_cnt >= (num_of_slides-1)) {
        slidesReady();
    }
}
function preload() {
    // set a timeout for preloading. Currently set to 300 ms per image,
    // could be more dynamic given info about image size and connection speed
    lID = setTimeout('slidesReady()', 300*num_of_slides);
    for (i = 0; i < num_of_slides && lID != null; i++) {
        imgs[i] = new Image();
        imgs[i].src = pics[i];
        imgs[i].onLoad = isLoaded(); // example of functional-style/callback
    }
}

window.focus();
// following block parses the URL query string
// equivalent of $_GET['start'] only on the client side
// no error-checking is done here.
var loc_str = window.location + "";
URL_array = loc_str.split(/\?/);
var query_str = URL_array[URL_array.length - 1];
params = query_str.split(/&/);
for (i = 0; i < params.length; i++) {
	if (params[i].match(/start=/)) {
	    slide_num = parseInt(params[i].replace(/start=/, ""));
	}
}
// ---------------------------------
desc[0] = "An invisible 747";
pics[0] = "/photos/101.jpg";
desc[1] = "A Green Giraffe on Rollerblades";
pics[1] = "/photos/a_photo.jpg";
// ...
// slide data is statically defined here. of course it could come from anywhere, such as an AJAX request or crunching a hidden content on the page

Looks a bit like C, only without pointers, and with more built-in regular expression support. Not as OO as Java or Python. A quick read on the history of ECMAScript is useful. Admitted, this is not the most sophisticated example of JavaScript code, but the Big JS frameworks (around since ~2006) seem like an evolutionary step (paradigm shift?) from this. I am still wondering when/if browsers will just support the new coding conventions/functionality natively.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Copy This Password

Type Or Paste Password Here *

666 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>