Reputation: 6694
Is it possible to change the stlye of the text in a selection?
<p onmouseup="mouseUp()">This is a text for testing the selection</p>
<script>
function mouseUp() {
var selection = window.getSelection();
alert(selection.toString());
//can I cahnge the color of e.g. the first character of the selection?
}
</script>
Upvotes: 1
Views: 97
Reputation: 584
Try this - it works: click on the "T" and it will change to blue
<p onclick="mouseUp()">
<span id="first_Letter">T</span>his is a text for testing the selection
</p>
<script>
function mouseUp() {
var first_L = document.getElementById("first_Letter");
first_L.style.color = "blue";
}
</script>
Upvotes: 0
Reputation: 4158
I've already had this problem, and found the following explanation and implementation useful:
function surroundSelection(element) {
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(element);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
(taken from: Wrapping a selected text node with span)
EDIT: to also change the style, here is a simple example
<p onmouseup="surroundSelection()">This is a text for testing the selection</p>
<script>
function surroundSelection() {
var span = document.createElement("span");
span.style.fontWeight = "bold";
span.style.color = "green";
if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(span);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
Upvotes: 2
Reputation: 9681
You would need to wrap the first character in an element (span
for example) and then apply some css or a class to that element.
Upvotes: 0