SHC MostWanted
SHC MostWanted

Reputation: 111

How to make a span from user selection (js)

I want to make a text editor. It should work the way all text editors work (including this one i am using right now), so the user makes a selection of the text, presses a button or whatever, and then some function is executed. I want my editor to work in the following way: 1. User selects 2. Function selected() is triggered that makes a span around the selected text. 3. When user clicks a button such as "B" or "I", they invoke functions that change .style of the span element. For now I figured out how to get string from user selection, nothing more than that.

    <body>
        <textarea onselect="selected()">Some text here, more text here.</textarea>
    </body>
    <script>
        function selected() {
var preselection = window.getSelection();
    selection = preselection.toString();
    console.log(selection);
}
    </script>

Upvotes: 2

Views: 703

Answers (1)

TheCodePig
TheCodePig

Reputation: 122

textareas can't contain spans, so you will need to use something like this if you decide to use spans:

<p contenteditable="true" ...

You probably don't want to fire your function every time a user makes a selection. Instead, just run the function if a user presses a button (like the bold button) and then pick up the selected text, if any, using something like:

document.getSelection().toString()

Now adding a <span> object to an HTML element is pretty easy, but the big challenge here is that you don't know if your selection will cross other span objects (like if the user already added some formatting). Notice that stackoverflow inserts characters like ** in the edit area and then does one pass to add in tags like <strong>. This is possible in a text area as well, so you wouldn't need contenteditable="true".

It is possible to analyze what is in your selection and then collect all elements involved, and rewrite them as needed. You would have to get all parent objects involved in the selection and then add <span> elements around the text inside each of the parent objects.

To simplify this, you might make a rule that only one level of tags is allowed in your editable region, and then always re-write for that so that the results would only have one level of span:

<span class="bold">This whole sentence is italic and </span><span class="italic_bold">this half is also bold.</span> with no nesting of these span tags.

Investigating these properties might help with dealing with nesting: https://developer.mozilla.org/en-US/docs/Web/API/Selection

These string commands might also help: https://www.w3schools.com/jsref/jsref_obj_string.asp

Upvotes: 2

Related Questions