O. Shekriladze
O. Shekriladze

Reputation: 1536

Blur input without calling Blur() function

I have angular custom input element. Now what I want to do is to blur this input programmatically using javascript. My special case is that I don't want to touch input itself. For instance, when I click some other document element on screen, input blurs, but when I call click() function on this dom element, it doesn't. So how can I blur it without touching input?

Upvotes: 0

Views: 1396

Answers (2)

Kaiido
Kaiido

Reputation: 136716

To be able to blur your input without touching it, you need to focus an other element.

One could think that simply calling focus() on the default document.activeElement (<body>) would do, but it doesn't... Browsers all differ on this, and that's one part of the specs I still struggle a lot to get my head off.

What all browsers agree on though is that an element with a tabindex != -1 attribute can be focused programmatically. So you could always set that attribute on the body of the document, that shouldn't change default focus behavior of your doc.

document.body.tabIndex = 0;
document.querySelector( 'input' ).onfocus = (evt) => {
  console.log( 'will blur in 2s' );
  setTimeout( () => {
    console.log( 'blurring' );
    document.body.focus()
  }, 2000 );
};
<input placeholder="click here to gain focus">

Upvotes: 2

Barremian
Barremian

Reputation: 31125

The question is unclear at the moment. You need to provide more code.

That said, you could use Angular template reference variable to blur or focus the input element. Try the following

Template

<input #customInput type=text placeholder="Enter your name"/>

<button (mouseup)="blurInput(customInput)">Blur input</button>
<button (mouseup)="focusInput(customInput)">Focus input</button>

Here customInput is the template reference variable of the input element.

Controller

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  blurInput(input) {
    input.blur();
  }

  focusInput(input) {
    input.focus();
  }
}

Working example: Stackblitz

Upvotes: 0

Related Questions