Solution for Jerome

by alano

HTML

<div id="main">
    <!--We will hide this when we load the target page-->
    <h1>Contents List</h1>
    <ul id="theList"></ul>
</div>
<div id="thePage">
    <!--This is where we will load the target page-->
</div>

CSS

ul#theList li {
    cursor: pointer;
    color: Blue;
    text-decoration: underline;
}

JavaScript

//IMPORTANT: this code will only execute if the target url's are exist on the domain where this page is being hosted 

var promises = [], links = [], urls = [
    'http://www.austudio.fr/jerome/files/idfile1.html',
    'http://www.austudio.fr/jerome/files/idfile2.html'];

function ALink(aUrl) {
    //force the "new" keyword at each instantiation
    if (typeof ALink != "function") return new ALink(aUrl);
    //return a "promise" back to the caller
    return $.ajax({
        url: aUrl,
        success: function(data) {
            var aLink = {};
            $("h1", data).each(function () {
                //once a page loaded, save details of each <h1> into "links" array 
                links.push({
                    url: aUrl, 
                    h1ID: $(this).attr("id"), //not used
                    h1Text: $(this).text()
                });
            });
        }
    });
}

function scrollToJQElement($jq) {
    //scroll the targetted <h1> to top of page for ease of viewing
    $('html, body').animate({
        scrollTop: $jq.offset().top
    }, 750);
}

function h1Go(idx) {
    //hide the Contents because we will load the desired page inside this one!
    $("div#main").hide();
    var theLink = links[idx];
    //load the page clicked by user
    $("div#thePage").load(theLink.url, function () {
        //find the <h1> that contains the matching text
        var $match = $("h1:contains('" + theLink.h1Text + "'):first");
        scrollToJQElement($match);
    });
}

function buildList() {
    var theLinks = "";
    $.each(links, function (idx, link) {
        //build an <li> and make it look like a hyperlink
        theLinks += "<li onclick='h1Go(" + idx + ")'>" + link.url + " : " + link.h1Text + "</li>";
    });
    //add all the <li>'s to the page
    $("ul#theList").html(theLinks);
}

//THE WHOLE PROCESS STARTS HERE, once the initial Contents page has loaded...
$(document).ready(function () {
    $.each(urls, function(i, u) {
        //load each page...