Skip to content

Instantly share code, notes, and snippets.

@davidjb
Last active August 13, 2017 08:32
Show Gist options
  • Save davidjb/5801924 to your computer and use it in GitHub Desktop.
Save davidjb/5801924 to your computer and use it in GitHub Desktop.
Replace HTML paragraphs with incremental identifiers, and create custom tooltips via JavaScript with jQuery Tools.
jQuery(function($) {
$(window).ready(function() {
var reference_url = '//terrestrialclimatechange.org.au/references';
var storage_key = 'references.data';
var ref_link_structure = function(reference) {
return '<a href="' + reference_url + '#ref-' + reference + '">' + reference + '</a>';
};
var tooltip_structure = function(content) {
return $('<div class="tooltip" />').append(content);
};
var replace_references = function(data) {
// Handle issue if page is not accessible
if (data.search('#content') != -1) { return false; }
var references = $('<div />').append(data);
//Process references into an associative array?
$('sup').each(function(index, element) {
var text_refs = element.innerHTML.replace(' ', '').split(',');
var ref_found = false;
//var tooltip_structure = $('<sup />');
var ref_structure = [];
for (var i = 0; i < text_refs.length; i++) {
var text_ref = text_refs[i];
//Warning: this will strip trailing characters from a valid int
var parsed = parseInt(text_ref);
if (!isNaN(parsed)) {
var tooltip_content = references.find('#ref-' + parsed).clone().removeAttr('id');
if (tooltip_content.length > 0) {
ref_structure.push(ref_link_structure(parsed));
ref_structure.push(tooltip_structure(tooltip_content)); //Remove ID here?
ref_found = true;
}
}
}
if (ref_found) {
//Replace the given element's HTML and then run tooltip initialisation.
element.innerHTML = '';
for (var i = 0; i < ref_structure.length; i++) {
$(element).append(ref_structure[i]);
}
$(element).find('> a').tooltip({
position: 'bottom center',
relative: true
});
}
});
};
var reference_data;
// Attempt loading data from local storage, if available
if (Modernizr.localstorage) {
reference_data = localStorage.getItem(storage_key);
if (reference_data) {
replace_references(reference_data);
}
}
// If local storage is unavailable, then load from the server.
if (!reference_data) {
$.get(reference_url + '/CookedBody',
function(data, textStatus, jqXHR) {
replace_references(data);
if (Modernizr.localstorage) {
localStorage.setItem(storage_key, data);
}
}
);
}
});
});
import re
#Page content here.
content = open('page_content.html', 'rb').read()
#Starting reference index to inject into paragraphs
reference_index = 1
def rework_paragraphs(m):
global reference_index
value = '<p id="ref-%i">' % reference_index
reference_index += 1
return value
print(re.sub('<p>', rework_paragraphs, content))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment