RachelD
RachelD

Reputation: 4089

Make a custom text editor (styler) with JS

I have been asked to create a text editor with the following features:

What is the best way to do this?

I have been playing with execCommand and this does most of what I want, except I cant seem to make the text non-editable, I'm not able to add chars before and after the selection like this, and I cant track individual changes.

I'm almost thinking I should make each word a label and treat them like objects but I'm having a hard time making them select-able (highlight the text with the mouse like you do in an editor).

Does anyone know of any libraries for this sort of thing?

Upvotes: 1

Views: 892

Answers (1)

pmrotule
pmrotule

Reputation: 9692

I can give you a part of the solution: how to select full words. My script is for textarea but you can make a few changes if you want to use div contenteditable instead.

JSFIDDLE DEMO

var lastSelectStart = 0;
var lastSelectEnd = 0;

saveSelection = function(){
    lastSelectStart = document.getElementById("text").selectionStart;
    lastSelectEnd = document.getElementById("text").selectionEnd;
}

selectWords = function(){

    var divEditable = document.getElementById("text");
    html = divEditable.innerHTML;

    var start = lastSelectStart;
    var end = lastSelectEnd;

    var before = html.substring(0,start);
    var after = html.substring(end);

    var split = before.match(/[ .,;]/gi);
    var startIndex  = before.lastIndexOf(split[split.length-1]) + 1;

    split = after.match(/[ .,;]/gi);
    var endIndex = after.indexOf(split[0]);
    endIndex = end + endIndex;

    divEditable.selectionStart = startIndex;
    divEditable.selectionEnd = endIndex;
    // startIndex is where you insert your stars and
    // (endIndex + number of stars added) is where you insert your stars again
}

Upvotes: 1

Related Questions