How to select all the text in div contenteditable


#1

I have a very simple custom element

<template>
  <!-- <div class="code" mouseup.delegate="onMouseUp($event)" focus.trigger="onFocus($event)" contenteditable textcontent.bind="value"></div> -->
    <div class="code title" data-placeholder.bind="placeholder" contenteditable textcontent.bind="value"></div>  
</template>

How can I select all of the text onFocus and onMouseUp?

I’ve tried all the following (commented out code) without success :blush:

@autoinject
export class AccountCodeCustomElement {
    @bindable({ defaultBindingMode: bindingMode.twoWay }) public value: IAccountCode;
    @bindable public placeholder = "Hello";

    constructor(private readonly el: Element, private readonly taskQueue: TaskQueue) {
        // $("div.code").on("focus", function() { $(this).select(); });
    }

    // protected attached() {
    //     $(this.el.querySelector(".code")).on("focus", () => $(this).select());
    //     $(this.el.querySelector(".code")).on("mouseup", () => $(this).select());
    // }

    protected onMouseUp(event) {
        console.log(event);
    }

    protected onFocus(event: Event) {
        console.log(event.srcElement.childNodes[0]);
        console.log(event.srcElement);

        const range = document.createRange();
        range.setStart(this.el, 0);
        range.setEnd(this.el, 1);


        // const codeElement = this.el.querySelector(".code");
        // this.taskQueue.queueMicroTask(() => {
        //     // console.log($(".code"));
        //     $(".code").select();
        // });


    }
}

#2

jQuery select is an event handler that fires when the user selects text. To programmatically select text you can see a simple example here


#3

I just can’t get that code to work!

It correctly selects the contents of the div for code.name, code.currency, code.type, code.a and code.e. However, for code.b, code.c, code.d I can’t even click into the custom element.

My view looks like:

 <div repeat.for="code of accountCodes" click.delegate="rowClicked($index)">
        <div class="d-flex justify-content align-items-start">
          <i class="fas fa-fw fa-trash text-danger cursor-pointer pt-2" click.delegate="deleteCode($index)"></i>

          <account-code placeholder="[Name of account code]" class="w-50 ml-2 code.selected ? 'text-danger' : ''"
                        code.bind="code" value.bind="code.name"></account-code>

          <select class="custom-select w-25 ml-2" code.bind="code" value.bind="code.currency">
            <option repeat.for="currency of currenciesList" model.bind="currency">${currency.name}</option>
          </select>

          <select class="custom-select w-25 ml-2" code.bind="code" value.bind="code.type">
            <option repeat.for="dbCr of debitCreditList" model.bind="dbCr">${dbCr}</option>
          </select>

          <account-code code.bind="code" value.bind="code.a"></account-code>
          <account-code code.bind="code" value.bind="code.b"></account-code>
          <account-code code.bind="code" value.bind="code.c"></account-code>
          <account-code code.bind="code" value.bind="code.d"></account-code>
          <account-code code.bind="code" value.bind="code.e"></account-code>
          <account-code code.bind="code" value.bind="code.f"></account-code>
</div>

account-code-element.html

<template>  
    <div class="code title" data-placeholder.bind="placeholder" mouseup.delegate="onMouseUp()" focus.trigger="onFocus()" contenteditable textcontent.bind="value"></div>  
</template>

account-code-element.ts

 protected onFocus() {
        // this.select();
    }

    protected onMouseUp() {
        // this.select();
    }

    private select() {
        let range: Range;

        const sel = document.getSelection();

        if (sel.toString() === "") {
            this.taskQueue.queueTask(() => {
                range = document.createRange();
                range.selectNodeContents(this.el);
                sel.removeAllRanges();
                sel.addRange(range);
            });
        }
    }

code is IAccountCode

export interface IAccountCode {
    key?: string;
    a: number;
    b: number;
    c: number;
    d: number;
    e: number;
    f: number;
    name: string;
    currency: ICurrency;
    type: "Db" | "Cr";
    selected?: boolean;
}

Tabbed from code.type to code.a

Tabbing from code.a to code.bhighlights the field but does not allow me to edit it.
If I keep tabbing, on arriving at code.e the last box is selected.


#4

Have you made it work? If not, what is the issue and would be nice if you can share a gist / repro.


#5

@jeremyholt can you be more specific about what is working and what isn’t? From your latest post I assume text selection works, but you can’t edit the content. Am I right? And repeating @bigopon - please provide gist. Try to share the most simple gist that reproduces the problem.


#6

Hi guys,

I’ve created a repo at https://github.com/jeremy-holt/SelectTextIssue2/tree/master/src

Just au run and you will see the problem.

I’m sure I’m just missing something really obvious.

I would also add that this is the first time I’ve ever seen/used code that directly speaks to window or document - goes to show how aurelia has kept me away from the dom for so long!

Many thanks in advance for your assistance
Jeremy


#7

By the way, when creating the new project for the example

yarn add aurelia-cli global
au new --here
select all the webpack options + typescript + defaults
au build fails

(aurelia-cli version = ‘1.0.0-beta.6’)

Incomprehensible error message …

I was able to create the new project selecting the internal builder with require.

Webpack !@!@#&!!!


#8

This is the right repo URL: https://github.com/jeremy-holt/SelectTextIssue2

For some reason this is what I see when I run yarn:

yarn install v1.9.4
[1/4] Resolving packages...
[2/4] Fetching packages...
[---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------] 0/738(node:26012) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
error An unexpected error occurred: "https://codeload.github.com/requirejs/text/tar.gz/d04de4ffd7bf5ba6cb80cdca2d40d4f6f52a1b1f: self signed certificate in certificate chain".
info If you think this is a bug, please open a bug report with the information provided in "d:\\projects\\jeremy-holt\\SelectTextIssue2\\yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

#9

My version of yarn is 1.12.3
I’m sorry - the correct link is https://github.com/jeremy-holt/SelectTextIssue2


#10

Gentle nudge … :grinning:


#11

@jeremyholt since I can’t run this repo locally, can you upload it to a shared platform like e.g. plunkr or jsfiddle?


#12

I’ll try - but I’ve never done that before.


#13

@jeremyholt I highly recommend to experiment with a couple. From reading here I learned about http://codesandbox.io/ that you can use to share Aurelia samples. For comparison, https://stackblitz.com provides an incredible platform for sharing Angular code. It’s practically VS Code on the web.

When you share your example, try to shrink it to minimum code that demonstrates the problem/question you wish to share and get help on.