Reputation: 11787
I am attempting to capture the text selected by a user, then append it below the selectable area. I do this by capturing the copy
event:
$("p").on("copy", highlight);
function highlight() {
var text = window.getSelection().toString();
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = $("<span class='highlight'>" + selectedText.textContent + "</span>");
selection.insertNode(span[0]);
if (selectedText.childNodes[1] != undefined) {
$(selectedText.childNodes[1]).remove();
}
var txt = $('#Text').html();
var re = new RegExp("<\/span>(?:\s)*<span class='highlight'>","g");
$('#Text').html(txt.replace(re, ''));
$("#output").append("<li>" + text + "</li>");
clearSelection();
}
function clearSelection() {
if (document.selection) {
document.selection.empty();
} else if (window.getSelection) {
window.getSelection().removeAllRanges();
}
}
This also handles the highlighting of text when the selected text overlaps text that might be currently highlighted. I then append the selected text below the selectable area through:
$("#output").append("<li>" + text + "</li>");
The problem with this is that if the user selects some text, then selects a part of that text, it will append each section below (as it should). Here's what I mean (the brackets indicate the selected text):
Suspendisse [dictum] feugiat nisl ut dapibus.
Will append dictum
below:
[Suspendisse [dic]tum] feugiat nisl ut dapibus.
Will append Suspendisse dic
below.
This is standard, but causes for multiple parts of a highlighted area to be added below, while they are merged in the selectable text.
So, how can I merge the text that is appended below so that it mimics the highlighted text that was merged?
A live example of the code I posted is here: http://jsfiddle.net/charlescarver/FLwxj/77/
Upvotes: 2
Views: 81
Reputation: 1168
Here's an option for achieving this. I'm not going to claim that this is the best or most efficient way to do this, but it does work.
Replace this line from your Javascript:
$("#output").append("<li>" + text + "</li>");
With these lines of code:
$('#Text').html($('#Text').html().replace(/<\/span><span class="highlight">/g, ''));
$('#output').html('');
$('#Text span.highlight').each(function() {
$('#output').append("<li>" + $(this).text() + "</li>");
});
Here's a branch of your Fiddle showing this.
Upvotes: 2