Is there way to get caret position from TextField?

Hello,

Is there way obtain caret (cursor) position, Integer value, from com.vaadin.flow.component.textfield.TextField?

Br., Janne

I can only think of an ugly hack. I used a TextField with ValueChangeMode.EAGER in the example here so that I get events immediately when something changes in the input:

        TextField textField = new TextField("Hello");
        textField.setValueChangeMode(ValueChangeMode.EAGER);
        textField.addValueChangeListener(e -> {
            UI.getCurrent().getPage().executeJs(
                    "return $0.shadowRoot.children[1]
.children[1]
.children[1]
.children[0]
.selectionStart;"
                    , textField.getElement()).then(Integer.class, integer -> {
                Notification.show("Cursor is at " + integer);
            });
        });

This will break if the internal DOM structure of TextField changes.

Being able to know the cursor position sounds like a useful feature, though, so I’d recommend creating a ticket at https://github.com/vaadin/vaadin-text-field

This opened ticket has been opened: https://github.com/vaadin/vaadin-text-field/issues/515

Thank you very much about this, I will try this out.

The chain of children looks really flaky. If anything in the internal DOM structure changes, then that chain of calls may break. I think a more reliable to query for the input directly. The input has part=value defined.

TextField textField = new TextField("Hello");
textField.setValueChangeMode(ValueChangeMode.EAGER);
textField.addValueChangeListener(e -> {
	UI.getCurrent().getPage().executeJs(
	"return $0.shadowRoot.querySelector('[part="value"]
').selectionStart;"
	, textField.getElement()).then(Integer.class, integer -> {
		Notification.show("Cursor is at " + integer);
	});
});