A solution that I came up with is as follows.
HTML:
<p>Semper mi vitae tellus <span class="date" title="19/03/09" data="19th of March">19th of March</span> quis, augue.</p>
CSS:
.date {
display:inline-block;
text-align:center;
}
This stops the text from jumping around when the content is replaced.
Javascript:
var travel = function(node, noChildren){
if (node.firstChild && !noChildren) {
return node.firstChild;
}
if (node.nextSibling) {
return node.nextSibling;
}
return travel(node.parentNode, true);
};
var onMouseDown = function(event){
var spans = document.getElementsByClassName(revertClass);
var i = spans.length;
while (i) {
i--;
spans[i].innerHTML = spans[i].getAttribute('data');
spans[i].className = window.baseClass;
}
var selection = window.getSelection();
if (selection.rangeCount && event.button === 2){
var n = selection.rangeCount;
var k = n;
do {
var i = k-n;
var range = selection.getRangeAt(i);
var element = range.startContainer;
var endContainer = range.endContainer;
do {
if (element.className === window.baseClass){
element.style.width = element.offsetWidth;
element.innerHTML = element.title;
element.className += ' ' + window.revertClass;
}
if (element == endContainer){
break;
}
}
while (element = travel(element));
var newRange = document.createRange();
newRange.setStart(range.startContainer, range.startOffset);
newRange.setEnd(range.endContainer, range.endOffset);
selection.removeRange(range);
selection.addRange(newRange);
}
while (--n);
}
};
var onKeyDown = function(event){
//Ctrl + C
if (event.keyCode === 67 && event.ctrlKey){
event.button = 2;
onMouseDown(event);
}
//Tab to deselect
else if (event.keyCode === 9){
onMouseDown(event);
}
};
window.baseClass = 'date';
window.revertClass = 'date_revert';
window.addEventListener ('mousedown', onMouseDown, false);
window.addEventListener ('keydown', onKeyDown, false);
I purposely didn't use jquery as I'm planning on using this in a greasemonkey script and loading it on every page would slow things down (I think?). I had it working with it automatically changing on selection by binding mousemove after mousedown fired but it ended up being very slow so I decided it was best to focus on my goal of changing what was copied.
About the usage of non standard attributes, I've never found this to be a problem? I'm using title so that people can see the alternative format without copying it and data because it seemed logical.