Reputation: 408
so I'm trying to highlight user selected text. Essentially the user can drag the mouse (while clicked) to select some random text on the page (anything within<p>
tags). On mouseup I want to change that text to be highlighted and bold.
The requirements for this are that the text selected and ONLY the text selected gets highlighted. So no matching text in another <p>
tag, and no matching text within the same <p>
tag.
Now, this is what I have thus far for CSS:
span.highlight {
background-color: yellow;
font-weight: bold;
}
And what I have for jQuery:
function getSelected() {
var selected = '';
if (window.getSelection) {
selected = window.getSelection().toString();
} else if (document.getSelection) {
selected = document.getSelection();
} else if (document.selection) {
selected = document.selection.createRange().text;
}
}
$(document).ready(function() {
$('p').live('mouseup', function() {
var selected = getSelected();
$(this).html($(this).html().replace(selected, '<span class="highlight">' + selected + '</span>'));
});
});
Now this works almost. However it will select the first instance of the selected text and highlight that, which isn't what I want, I want it to select the actual selected text. And it has one more problem, once some text is highlighted, if I select more text that includes part of the highlighted text, it won't change it.
I'm wondering if anyone can help with either of these issues? Thanks in advance.
EDIT:
Sorry, I should have also mentioned that I can't use a plugin. I've taken a look at them and most of them work for my needs quite well, but I can't use them.
Upvotes: 2
Views: 4770
Reputation: 604
In the past with good results.
However in your example look at the .replace function. try .replaceAll instead.
Upvotes: 2