Reputation: 8818
I want to highlight feature which will change the color of the selected text using Javascript. I am using the following method.
function android_selection_highlight(replacrmenthtml){
try {
if (window.getSelection) {
sel = window.getSelection();
var range = sel.getRangeAt(0);
var selectionStart = $("<span style=\"color:red\">");
var startRange = document.createRange();
startRange.setStart(range.startContainer, range.startOffset);
var selectionEnd = $("</span>");
var endRange = document.createRange();
endRange.setStart(range.endContainer, range.endOffset);
startRange.insertNode(selectionStart[0]);
endRange.insertNode(selectionEnd[0]);
}
}
catch (e) {
}
}
But it is giving DOM exception when I am calling the method. I think that when I am inserting starting span tag in front of the selected text, it is disrupting the DOM structure as there is no end tag at that moment. How to solve this problem?
Edited: There will a highlight button. Selecting the text, if user click on the highlight button, the text color of the selected text will change.
Upvotes: 1
Views: 1268
Reputation: 26
The CSS Custom Highlight API, https://developer.mozilla.org/en-US/docs/Web/API/CSS_Custom_Highlight_API, is designed to do exactly what you want. In JS you can mark ranges as having a named highlight style, and in CSS you define what that highlight is. The browser should do something that looks like selection, but is persistent.
For example:
<style>
div::highlight(foo) {
background-color: green;
}
</style>
<div id="highlighted">This is highlighted text</div>
<script>
let r = new Range();
r.setStart(highlighted, 0);
r.setEnd(highlighted, 1);
let h = new Highlight(r);
CSS.highlights.set('foo', h);
</script>
Upvotes: 0
Reputation: 4641
if on select u want to change color use this code.
::-moz-selection { color: red;}
::selection { color: red; }
Upvotes: 6
Reputation: 4841
I know that this is a JS question, but there is a CSS selector which allows you to do this.
::selection {
color: red;
}
If the browser considers that you've made a choice which is not accessible, it might override your colours. Not everything can be styled in this way, but colours and background colours can.
More information:
Upvotes: 1