I am falling in a problem where I have descriptive raw text like this -
<p>I am using the following code to change the color of text but it is not working.. Can anyone help me with this? the soloution in javascript or jquery anything is fine..</p>
Now my requirement is
- To find position(range) of particular selected text on mouse up event
- make coloured the selected text during the whole operation
My written code
$(document).ready(function() {
if (!window.Wafer) {
Wafer = {};
}
Wafer.Selector = {};
/* Function to get selected string as a object
* works for all browser and also handle for old browser like
* ie9,firfox 18 as discussed
*/
Wafer.Selector.getSelected = function() {
$selObj = '';
if (window.getSelection) {
$selObj = window.getSelection();
} else if (document.getSelection) {
$selObj = document.getSelection();
} else if (document.selection) {
$selObj = document.selection.createRange().text;
}
//console.log($selObj);
return $selObj;
}
//holding the selector string in variable on mouseup event
Wafer.Selector.mouseup = function() {
$selector = Wafer.Selector.getSelected();
$start = $selector.anchorOffset;
$end = $selector.focusOffset;
console.log($start, $end);
//I call this to wrap selected text under span
selectText('#f90');
}
//This will tell jquery to fire when "mouseup" event will occur
$(document).on("mouseup", Wafer.Selector.mouseup);
});
function selectText(hexColor) {
var selection = window.getSelection().getRangeAt(0);
var selectedText = selection.extractContents();
var span = document.createElement('span');
span.style.backgroundColor = hexColor;
span.className = 'selected-text';
span.appendChild(selectedText);
selection.insertNode(span);
}
in function selectText I used to get window.getSelection().getRangeAt(0); which might conflict with window.getSelection() and both are returning object which has anchoroffset and focusoffset key so unable to get proper text range
Is there any way to clear text range which is selected?
Followed couple of stack posts like this but those are partially filling my requirement and having buggy code. Thanks in advance.