0

I am a iPhone app developer.I am changing the color of selected text. This is working fine for me. But when there are few repeated words for example

Hi All.Hello world.I am iPhone app developer.Hello world.Stack overflow.Hello world.

Here 'Hello' text is repeating. When i am selecting last 'Hello' text it is giving me first 'Hello' text index. I tried indexOf(),search() and anchorOffset() but this is not working.

Following is my code.

function heighlightText(data) {
    var selectedText = window.getSelection();

    var textd=$("#data").html(); // this will give me whole text.

    var normalText = $("#data").text();
    var startPosition = normalText.search(selectedText);                        // this will give selected text start position.
    var getPosition = selectedText.toString();
    var endPosition = parseInt(getPosition.length) + parseInt(startPosition);   // this will give selected text end position.

    var textToReplace = "<span id='" + startPosition + "' class='highlightedText' onclick=\"myOnclikFunction('"+selectedText+"')\"> "+selectedText+"</span>";

    var startPart = textd.substr(0,startPosition);
    var lastPart = textd.substr(endPosition,textd.length);
    var reT = startPart + textToReplace + lastPart;

    $("#data").html(reT);
}

Hy HTML:

<style type = "text/css">
    #data {
        font-size : 20px;
        color : black;
    }

    .highlightedText {
        background-color : red;
    }
</style>

<body>
    <div id = "data" >Lots of text here...
    <div/>
</body>

Can any one suggest solution for this. Thanks in advance.

Sujit
  • 610
  • 7
  • 26

3 Answers3

2

If you're just colouring the text, then Stefan's answer is the most reliable and easiest way:

document.execCommand("ForeColor", false, "#0000FF");

However, it looks as though you're adding a class and a click handler, so you need more flexibility.

First, there is no way to get a selection as offsets within an HTML representation of the DOM reliably. You can get the selection as offsets within nodes directly via anchorOffset, anchorNode, focusOffset and focusNode, or as a DOM range. If the selection is completely contained within a single text node, you can use the range's surroundContents() method:

Demo: http://jsfiddle.net/UvBTq/

Code:

function highlightText(data) {
    var selection = window.getSelection();
    if (selection.rangeCount > 0) {
        var range = selection.getRangeAt(0);
        var selectedText = range.toString();

        var span = document.createElement("span");
        span.id = "span_" + range.startOffset + "_" + range.endOffset;
        span.className = "highlightedText";
        span.onclick = function() {
            myOnclikFunction(selectedText);
        };

        range.surroundContents(span);

        // Restore selection
        selection.removeAllRanges();
        selection.addRange(range);
    }
}

However, this is very brittle and will only work when the selection is completely contained within a single text node. Depending on what you're trying to do, you may need a more flexible solution.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

To get the selected text, you have to use the getSelection javascript method. i don't know if that method is available on iphone browser, but here is a general function that combines the methods for all browsers.

function getSelected() {
    var text = "";
    if (window.getSelection
    && window.getSelection().toString()
    && $(window.getSelection()).attr('type') != "Caret") {
        text = window.getSelection();
        return text;
    }
    else if (document.getSelection
    && document.getSelection().toString()
    && $(document.getSelection()).attr('type') != "Caret") {
        text = document.getSelection();
        return text;
    }
    else {
        var selection = document.selection && document.selection.createRange();

        if (!(typeof selection === "undefined")
        && selection.text
        && selection.text.toString()) {
            text = selection.text;
            return text;
        }
    }

    return false;
}

found here

Community
  • 1
  • 1
Bastian Rang
  • 2,137
  • 1
  • 19
  • 25
0

Use contenteditable="true" and document.execCommand('ForeColor', false, 'YOURCOLOR'); instead

Example:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title>- jsFiddle demo</title>

    <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
    <script type='text/javascript'>
        $(function () {
            $('#color').click(function () {
                document.execCommand('ForeColor', false, '0000FF');
            });
        });
    </script>
</head>
<body>
    <p contenteditable="true">Hello world</p>
    <button id="color">Change Color</button>
</body>
</html>

Fiddler: http://jsfiddle.net/WQKCw/1/

Stefan
  • 14,826
  • 17
  • 80
  • 143
  • Why the downvotes? This is a good answer, although the code in the question does seem to imply that the `` used to surround the selected text is doing more than just colouring the text. – Tim Down Jan 04 '13 at 09:26
  • nice somebody is wondering too. Well their is another document.executeComand for creating spans but I can't find it at the moment... – Stefan Jan 04 '13 at 09:44
  • 1
    There's `InsertHTML` but that pastes over the existing selection rather than surrounding it. – Tim Down Jan 04 '13 at 09:55