From 3d8ae2e7438a8895582bc372816094c644ecddbd Mon Sep 17 00:00:00 2001 From: Peter Wu Date: Wed, 8 Apr 2015 10:05:16 +0200 Subject: Fix anchor focussing and page navigation --- js/curriculum.js | 4 ++-- js/main.js | 35 +++++++++++++++++++++++++++-------- 2 files changed, 29 insertions(+), 10 deletions(-) (limited to 'js') diff --git a/js/curriculum.js b/js/curriculum.js index 164ff3b..9b35cc4 100644 --- a/js/curriculum.js +++ b/js/curriculum.js @@ -44,7 +44,7 @@ define(['courses'], function(courses) { // display link for courses which have a description block if (course.id) { var link = document.createElement('a'); - link.href = '#!/curriculum/' + course.id; + link.href = '#/curriculum/' + course.id; link.textContent = course.name; course_item.appendChild(link); } else { @@ -56,7 +56,7 @@ define(['courses'], function(courses) { courses.courses.forEach(function(course) { var header = document.createElement('h2'); //header.id = 'course-' + course.id; - header.id = '!/curriculum/' + course.id; + header.id = '/curriculum/' + course.id; header.textContent = course.name + ' (' + course.when + ')'; citems.appendChild(header); diff --git a/js/main.js b/js/main.js index 66d5be4..d37c228 100644 --- a/js/main.js +++ b/js/main.js @@ -29,33 +29,52 @@ define(function() { } /* tries to navigate to a page */ - function selectPage(page) { + var current_page; + function selectPage(page, anchor) { if (all_pages.indexOf(page) == -1) { // TODO: 404 console.log("404 " + page); return false; } + + if (current_page === page) { + return; + } + current_page = page; + console.log("Loading " + page); var http = new XMLHttpRequest(); http.onload = function() { loadContent(page, http.responseText); + + // focus element when loaded + var anchor_id = /^#(.+)/.exec(anchor); + if (anchor_id) { + var selection = document.getElementById(anchor_id[1]); + if (selection) { + selection.scrollIntoView(); + } + } }; http.open('get', 'pages/' + page + '.html' + cacheBuster); http.send(null); return true; } - addEventListener('hashchange', function(ev) { - var m = /#\/(.+)/.exec(ev.newURL); + function changePageHash(hash) { + var m = /#\/([^\/]+)/.exec(hash); if (m) { - selectPage(m[1]); - } else if (!/#/.test(ev.newURL)) { + selectPage(m[1], hash); + } else { location.hash = '#/home'; + selectPage('home', hash); } + } + + addEventListener('hashchange', function(ev) { + changePageHash(ev.newURL); }); // Tries to load the current page, falling back to "home" for unknown URLs. - if (!selectPage(location.hash.replace(/^#\//, ''))) { - location.hash = '#/home'; - } + changePageHash(location.hash); }); -- cgit v1.2.1