2

I want to select text thats is on a Html page and make it BOLD, I am using the following Code

<script type="text/javascript" >


function getSelectedText(){ 
    if(window.getSelection){   ;
        return window.getSelection().toString(); 
    } 
    else if(document.getSelection){;
        return document.getSelection(); 
    } 
    else if(document.selection){ ;

        return document.selection.createRange().text; 
    } 
} 
$(document).ready(function(){
 $("*").live("mouseup",
    function() {
        selection = getSelectedText(); 
        alert(selection);
        if(selection.length >= 3) {

            $(this).html($(this).html().replace(selection, "<b>" + selection + "</b>") );

        }       
    }
); 
});

</script>

This Code works Fine But when the text is in two different paragraphs/ Div or if there is a link between the text then it doesnt seem to work.

How Could i Make it Work ?

11
  • How about somehow initiating a browser search (Ctrl+F) from javascript? But, I don't know how to do that from javascript. Commented Jan 25, 2011 at 8:36
  • You just wanna select the text or the additional tags too? And what is the purpose of just selecting it? It would help if you explained what do you want to do with the text. Commented Jan 25, 2011 at 8:44
  • @pea window.find(string) Commented Jan 25, 2011 at 9:11
  • 1
    That will work fine for obtaining just the text that is selected but will not tell you anything about the HTML elements that contain the text. What do you actually want? Commented Jan 25, 2011 at 9:24
  • @All - Its a Simple program, I just want the selected text to be Displayed on the screen . But when Two different paragraphs are selected then This Code doesn't seem to work ... Commented Jan 25, 2011 at 12:12

3 Answers 3

2

If you want to do some kind of highlighting of the current selection, using the built-in document.execCommand() is the easiest way. It works in all major browsers.

The following should do what you want on any selection, including ones spanning multiple elements. In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again.

UPDATE

Fixed to work in IE 9.

function makeEditableAndHighlight(colour) {
    var range, sel = window.getSelection();
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    document.designMode = "on";
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    // Use HiliteColor since some browsers apply BackColor to the whole block
    if (!document.execCommand("HiliteColor", false, colour)) {
        document.execCommand("BackColor", false, colour);
    }
    document.designMode = "off";
}

function highlightSelection(colour) {
    var range;
    if (window.getSelection) {
        // IE9 and non-IE
        try {
            if (!document.execCommand("BackColor", false, colour)) {
                makeEditableAndHighlight(colour);
            }
        } catch (ex) {
            makeEditableAndHighlight(colour)
        }
    } else if (document.selection && document.selection.createRange) {
        // IE <= 8 case
        range = document.selection.createRange();
        range.execCommand("BackColor", false, colour);
    }
}

document.onmouseup = function() {
    highlightSelection("red");
};

Live example: http://jsfiddle.net/eBqBU/9/

Sign up to request clarification or add additional context in comments.

10 Comments

I Could not get this to work ... I called your function like this ====$("*").live("mouseup", function() { selection = highlightSelection(red) ;
@Adi: Works fine for me. You need to add quotes around "red". I've updated my answer with an example use, and a live example.
Wohh!!! Yahooo!! it worked !! it Worked!! :D Great Work!! One last question.. Is there a Way in which i could use my Own CSS for Highlighting , The code that I wrote up in that i could chage the CSS by the FOllowing line $(this).html($(this).html().replace(selection, "<span class='highlight'>" + selection + "</span>") );
@Adi: There's nothing to do that built into browsers. You need to iterate over the nodes within the selection and surround each with your span, which is fairly complicated to do in a cross-browser way. You could use my Rangy library and it's CSS class applier module to do this: code.google.com/p/rangy/wiki/CSSClassApplierModule
@Adi: The essential steps are: 1. split text nodes at the beginning and end of the selection; 2. create an array of text nodes that are contained within the range and 3. surround each text node in a <span> (unless it's already contained in a span with the relevant class).
|
0
a=document.getElementById('elementID').innerHTML;

variable 'a' will get the string value of anything inside the element with an id 'elementID'.

Is this ok?

1 Comment

Sir, I would like to get the contents that i have selected by the mouse, For example a Wikipedia's page. I want that When i click and Drag My mouse over 2 Paragraphs (selecting text) that is returned. The Code that i have mentioned Above doesn't work when the Content selected is across two different paragraphs or if there is a Hyperlink some where in between the text that i have selected.
0

Everything you need (based on your comments) can be found here: http://www.awesomehighlighter.com/webliter.js

I don't have time to extract the relevant parts but take a look for example in Webliter.prototype.highlight (just search for this in that file)

You can also use jQuery for example this plugin: http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html

3 Comments

Sir , The Highlight link that you gave will highlight, based on all the values searched in the Document , While i want it to highlight the things that i selected. Sir, Please Execute the Code that i wrote :)
@Adi I think the person who gave you the code has better chance of figuring this out. :)
Its all experimental code... Searching Here and there adding and modifying made be get that code :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.