Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - How can i set markers for selected text?

Tags:

javascript

I need to highlight a selected text with JavaScript (no jQuery) and having control points or markers (left and right), I don't really know how to call them, similarly like on mobile phones so I can extend the selection anytime by dragging any of the control points.

Example: http://screencast.com/t/KJBdvreeVW

I've grabbed the selected text, demo: http://jsfiddle.net/henrichro/HJ482/

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    alert(text);
}

if (window.Event) document.captureEvents(Event.MOUSEUP);
document.onmouseup = getSelectionText;

Now I have this working code to get the text, but I would like to have markers around it, as written above :)

Update 10/28/2013:

After Dementic's directions (his answer below), I figured out the next working code: http://jsfiddle.net/henrichro/WFLU9/

The only problem persists when I select more than one line. On that scenario the markers are showing wrong.


1 Answers

found a solution here : How do I wrap a text selection from window.getSelection().getRangeAt(0) with an html tag?

which uses just a bit of Jquery, modified it so its pure js (just removed the selectors and the onclick), you can find a working example here: http://jsfiddle.net/3tvSL/83/

this marks the selected text with yellow background, and will need a bit more work to have "Markers" on the sides.

as for an idea, you can use an absolute positioned div as the marker, and while it is dragged, you can use something like:

function expand(range) {
    if (range.collapsed) {
        return;
    }

    while (range.toString()[0].match(/\w/)) {
        range.setStart(range.startContainer, range.startOffset - 1);   
    }

    while (range.toString()[range.toString().length - 1].match(/\w/)) {
        range.setEnd(range.endContainer, range.endOffset + 1);
    }
}

Taken from: Select whole word with getSelection

one more thing, i have found a working js library to do exactly what you wish... http://www.mediawiki.org/wiki/Extension:MashaJS take a look :)

like image 131
Rafael Herscovici Avatar answered Sep 11 '26 06:09

Rafael Herscovici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!