[SOLVED] How to detect if input field is active?

Is there any way to detect if an input field has an active text cursor?

For example, in the image below

I would have a script attached to the screen of these different input elements that would detect that the input select is the active element.


Maybe something like this.entity.element.hasFocus?

Or something that returns the name of the active element, this.app.root.activeElement.tagname?

Hi @hooymana,

I think those are HTML DOM elements right? Since PlayCanvas doesn’t really has support for text inputs (yet hopefully :innocent: ).

For a DOM input element I think you can check if it has focus by checking it against the document active element:

if(document.activeElement === document.getElementById('your-input-id'){
   // input has focus

Thank you @Leonidas !

I am having difficulty identifying the input id. When I run a console.log(document.activeElement) in the script attached to Image1 Entity I can only see that each input field is called input.

Here is the editor for the scene.


Here are the scripts I am currently working on.


I’ve checked with the browser dev tools, your input field doesn’t have an ID to target it:

Easiest solution is to add an ID, or find another way to target it (e.g. study the document.querySelector method).

For example:

DigitText.prototype.initialize = function() {
    this.element = document.createElement('input');
    this.element.id = 'input-id';

Then use the input-id in your if statement:

if(document.activeElement === document.getElementById('input-id'){
   // input has focus
1 Like

Thanks again @Leonidas !

That works!

1 Like