From 9cc9029ae34b911ba15a26865a4f38939d201839 Mon Sep 17 00:00:00 2001 From: Peter Wu Date: Wed, 8 Apr 2015 10:52:12 +0200 Subject: Implement back to top handling --- js/curriculum.js | 7 +++++++ js/main.js | 35 +++++++++++++++++++++++++++-------- 2 files changed, 34 insertions(+), 8 deletions(-) (limited to 'js') diff --git a/js/curriculum.js b/js/curriculum.js index 9b35cc4..a93b2e4 100644 --- a/js/curriculum.js +++ b/js/curriculum.js @@ -63,6 +63,13 @@ define(['courses'], function(courses) { var text_block = document.createElement('p'); text_block.textContent = course.description; citems.appendChild(text_block); + + var links_block = document.createElement('p'); + var back_to_top = document.createElement('a'); + back_to_top.href = '#top'; + back_to_top.textContent = 'Back to top'; + links_block.appendChild(back_to_top); + citems.appendChild(links_block); }); }; }); diff --git a/js/main.js b/js/main.js index d37c228..7ae3fc1 100644 --- a/js/main.js +++ b/js/main.js @@ -48,9 +48,9 @@ define(function() { loadContent(page, http.responseText); // focus element when loaded - var anchor_id = /^#(.+)/.exec(anchor); + var anchor_id = extractHash(anchor); if (anchor_id) { - var selection = document.getElementById(anchor_id[1]); + var selection = document.getElementById(anchor_id); if (selection) { selection.scrollIntoView(); } @@ -61,10 +61,20 @@ define(function() { return true; } - function changePageHash(hash) { - var m = /#\/([^\/]+)/.exec(hash); - if (m) { - selectPage(m[1], hash); + function extractHash(url) { + var m = /#(.+)/.exec(url); + return m ? m[1] : ''; + } + function extractPageComponents(url) { + var m = /^\/([^\/]+)(.*)$/.exec(extractHash(url)); + return m ? [m[1], m[2]] : ['', '']; + } + + function changePageUrl(url) { + var m = extractPageComponents(url); + var hash = m.join(''); + if (hash) { + selectPage(m[0], hash); } else { location.hash = '#/home'; selectPage('home', hash); @@ -72,9 +82,18 @@ define(function() { } addEventListener('hashchange', function(ev) { - changePageHash(ev.newURL); + var anchor = extractHash(ev.newURL); + // magic key to jump to the top of the page. + if (anchor === 'top') { + var pageURL = '#/' + extractPageComponents(ev.oldURL)[0]; + scrollTo(0, 0); + location.replace(pageURL); + return; + } + + changePageUrl(ev.newURL); }); // Tries to load the current page, falling back to "home" for unknown URLs. - changePageHash(location.hash); + changePageUrl(location.hash); }); -- cgit v1.2.1