Caio
Caio

Reputation: 3215

Keep the selection in a textarea

Can I prevent the loss of selection in the "onblur" event?

<!DOCTYPE html>

<html xmlns = "http://www.w3.org/1999/xhtml" xml:lang = "en" lang = "en">
    <head>
        <meta http-equiv = "Content-Type" content = "text/html; charset=utf-8">

        <script type = "text/javascript">
            window.onload = function () {
                var textarea = document.getElementsByTagName ("textarea")[0];

                textarea.onblur = function () {
                    alert ("Should keep selection");

                    return false;
                }
            }
        </script>

        <title>Select me!</title>
    </head>

    <body>
        <textarea>Select me!</textarea>
    </body>
</html>

Upvotes: 2

Views: 2568

Answers (4)

Farshid Ahmadi
Farshid Ahmadi

Reputation: 513

I've prepare this js class for you:

class SelectionHolder{
    constructor(element_id){
        this.element = document.getElementById(element_id);
        this.selection_start = null;
        this.selection_end = null;
    }
    setListener(object){
        this.element.onfocus = ()=>{object.reselect();}
        this.element.onblur = ()=>{object.update();}
    }
    update(){
        this.selection_start = this.element.selectionStart;
        this.selection_end = this.element.selectionEnd;
    }
    reselect(){
        this.element.setSelectionRange( this.selsection_start, this.selection_end, "forward");
    }
}

Then use it for your elements

Let my_holder = SelectionHolder("my-text-area-id");
my_holder.setListener(my_holder)

Upvotes: 0

polyhedron
polyhedron

Reputation: 1590

textarea.onblur = function () {
    alert("Should keep selection");
    textarea.focus();

    return false;
}

Upvotes: 2

Sarfraz
Sarfraz

Reputation: 382919

I don't think that's a good idea. A user with mouse in his/her hand can click anywhere on the page. If you get him/her back into the textarea, it won't be following the principles of web accessibility.

Upvotes: 4

ironfroggy
ironfroggy

Reputation: 8125

Maybe you mean you want to remember the selection, even if the user focuses on another element, so that if they go back to the textarea, the same text will still be selected. Is this the case?

If so, I think the easiest thing would be to put the textarea in an iframe in the same domain. Each document maintains its own selection context. Of course, you'll need to read the data from the textarea, and probably copy it to a hidden field in your form, as you can't have fields in a form in another document, so you need to make a sort of proxy.

Upvotes: 4

Related Questions