0

Possible Duplicate:
Replacing selected with another text

I am new to JavaScript and jQuery`. I am selecting a word and on button click, I want to change the background color of that text.

I used a span tag to change the color of selected text and replace function to replace it.

But if the text is like

Hi all. Hello world. Good morning. Good morning.

When I am selecting last morning text, it is changing the background color of first morning text. I used replace function to replace the text.

Can anyone suggest solution for this.

Following is my code.

var selectedText = window.getSelection();

            var textd=$("#data").html();

            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 reT= textd.replace(selectedText,textToReplace);
            $("#data").html(reT);
      <style type = "text/css">

        #data {
            font-size : 20px;
            color : black;
        }

        .highlightedText {
            background-color : red;
        }

        .replaceBgColor {
            background-color: white;
        }

        </style>
      <body>

    <div id = "data" >From this you can tap on annotation to view the list of actions previously done like highlighting content, adding web links and notes. Tap on annotation you can view a popup with list of highlights, notes and web links where you can scroll the list.From this section you will be able to highlight part of content, add notes and web links. Upon long tap on the content a popup will be displayed where you can slide to select a part of content and select highlight option to highlight the content. From the same popup you will be able to add notes by tapping on notes button on the popup a text box will be displayed where you can enter the notes and save, you can also add web link in the same process by selecting add web link option in the popup.You can edit the notes and web links by selecting the annotations, where tapping on the annotations you can view the list, from the list you can select a particular notes or web link which will open in a text box to edit. After modification you can save or cancelTap on “View all highlights” to view all highlighted content in the selected material. Once you select view all highlights app will display all highlighted content, then “View all highlights” button will be changed to “Hide all highlights” which allows you to hide the highlight content.Tap on the “Related material” to view the related topics of the course selected and tap on videos to view the list of videos to view.My ClassesThis is the first screen after successful login, where you can view the classes list. Tap on the buttons to view current classes, past classes and future classes. You can tap on any option as per your choice from the three upon tapping the classes list will be shown in grid format with class details.You can tap on the following options to view classes:• Future Classes (The classes for which start date is after the current date)• Current Classes (The classes for which the current date is in between the start and end dates of particular class)• Past Classes (The classes for which the end date of class is before the current date)Based on the selection you can view the following class details:
        <div/>

        </body>
Community
  • 1
  • 1
Sujit
  • 610
  • 7
  • 26

3 Answers3

1

Try this:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
    <title>new document</title>
    <script type="text/javascript">
    function setColor(){
        if(document.all){
            var tr = document.selection.createRange();
            tr.execCommand("ForeColor", false, "#FF0000");
        }else{
            var tr = window.getSelection().getRangeAt(0);
            var span = document.createElement("span");
            span.style.cssText = "color:#ff0000";
            tr.surroundContents(span);
        }
    }
    </script>
</head>
<body>
<div>fdjlksafjd;slafjd;slakfjds</div>

<input type="button" onclick="setColor()" value="setColor" />
</body>
</html>
Ram
  • 143,282
  • 16
  • 168
  • 197
0

Maybe your code didn't know which morning is selected. Google Range or TextRange, this will be helpful!

Zhou Lee
  • 96
  • 4
  • Welcome to StackOverflow! Though this answer is marginally acceptable, be sure to make your answers more thorough and complete in the future! Thank you! –  Jan 08 '13 at 05:01
  • Thanks much.I aming always trying my best in writting an answer down correct,as English is not my first language. – Zhou Lee Jan 11 '13 at 02:29
  • No problem, we understand! Just do your best, and if something needs clarification, we'll ask. Otherwise, we will edit for clarity, spelling, and grammar. –  Jan 11 '13 at 02:31
0

See this : http://jsfiddle.net/Tru86/

hmtl:

 <div id = "data" >Hi all. Hello world. Good morning. Good morning.<div/>
 <input id="btn" type="submit" value="Highlight" />

Script:

$("#btn").click(function () {

  var selectedText = window.getSelection ? window.getSelection() : document.selection.createRange();  // second one for IE

  var textd = $("#data").html();
  var normalText = $("#data").text();
  if (selectedText.getRangeAt) {
    var range = selectedText.getRangeAt(0);
    var newNode = document.createElement("span");
    newNode.setAttribute('class', 'highlightedText');
    range.surroundContents(newNode);
  }
  else {
    selectedText.pasteHTML('<span class="highlightedText">' + selectedText.htmlText + '</span>');
  }
  $('.highlightedText').replaceWith(swapText);
});
Anujith
  • 9,370
  • 6
  • 33
  • 48
  • Thanks for your response.But there is a bug. like if user selected first hello world text, then according to this code it is changing background color. For next time if user selected text like Hi all Hello then it is not changing color. here Hi all Hello need to change background color. Can you suggest solution for this. This will helpful for me. Thanks – Sujit Jan 08 '13 at 06:38
  • @Sujit : See the updated fiddle..http://jsfiddle.net/Tru86/1/ – Anujith Jan 08 '13 at 07:41
  • 1
    @Sujit , accept as answer if it solved.. – Anujith Jan 08 '13 at 08:16