Tamaghna Banerjee
Tamaghna Banerjee

Reputation: 168

How to get selected text range and add color to the particular selected text

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 solution in Javascript or jQuery anything is fine..</p> 

Now my requirement is

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.

Upvotes: 2

Views: 2731

Answers (2)

Tamaghna Banerjee
Tamaghna Banerjee

Reputation: 168

Those who has this problem can get help in this way-

$("#text-box").mouseup(function () {
    var el = document.getElementById("text-box");
    getCaretCharacterOffsetWithin(el);
});

Function to get selection and find start and end range every time from parent container.

 function getCaretCharacterOffsetWithin(element) {
    var caretOffset = 0;
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;
    var sel;
    if (typeof win.getSelection != "undefined") {
        sel = win.getSelection();
        if (sel.rangeCount > 0) {
            var range = win.getSelection().getRangeAt(0);
            var preCaretRange = range.cloneRange();
            preCaretRange.selectNodeContents(element);
            preCaretRange.setEnd(range.endContainer, range.endOffset);
            caretOffset = preCaretRange.toString().length;
        }
    } else if ((sel = doc.selection) && sel.type != "Control") {
        var textRange = sel.createRange();
        var preCaretTextRange = doc.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
    }
    var start = caretOffset - sel.toString().length;
    var end = caretOffset - 1;
    if (start != end && end > start) {
        // Highlight the text
        console.log(start,end);
        var selectedText = range.extractContents();
        var text_value = selectedText.textContent;
        var span = document.createElement('span');
        span.style.backgroundColor = "red";
        span.className = 'selected-text';
        span.appendChild(selectedText);
        range.insertNode(span);
        $(".span").html(start + ",&nbsp;" + end);
        return caretOffset;
    }
}

Your HTML could be something like this

<div id="text-box" style="width: 700px; border:1px solid black">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum</div>

I have also added span tag to wrap the ranged text that is selected on mouseup event because I had a requirement to add color to field which gets selected. Hope this will help. :-)

Upvotes: 2

Hidayt Rahman
Hidayt Rahman

Reputation: 2678

Updated

Add color to particular text

$(".my").hrStringColor({
        string      : "Hi i am Hidayt Rahman. You can add your own", //optional
        charFrom    : 5,  // Index of character, where to start
        charTo      : 25, // Index of character, where to end
        color       : "green" // add your color
});

Might be it will help you, go there -> hrStringColor

Upvotes: 0

Related Questions