0

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?

4
  • How can an input be blurred if it never had focus? Commented May 26, 2020 at 10:02
  • Who said that? It has focus Commented May 26, 2020 at 10:05
  • Ok. That information looked like it was omitted. Especially since the words “without touching the input” were used. — What’s the context of this? Are you running a test of some kind? Commented May 26, 2020 at 10:09
  • Maybe try using jquery on the client-side script. api.jquery.com/blur Commented May 26, 2020 at 10:38

2 Answers 2

2

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">

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.