3

I am trying to implement an autocomplete input by using mdc web components. I have a menu selected event listener, where I want to deactivate focus on a textfield. I have tried that by using MDCTextFieldFoundation deactivateFocus method:

const inputFoundation = new MDCTextFieldFoundation(
  document.querySelector(".mdc-text-field")
);
menu.listen("MDCMenu:selected", e => {
  console.log(inputFoundation);
  input.value = e.detail.item.dataset.value;
  inputFoundation.deactivateFocus();
});

But, that is not working. In the console, I can also see that input's property isFocused is false, when textfield is still focused. You can see the whole codesandbox here. What am I doing wrong here and what is the correct way of deactivating focus from a textfield?

Leff
  • 1,968
  • 24
  • 97
  • 201

1 Answers1

1

From docs:

Deactivates the focus state of the Text Field. Normally called in response to the input blur event.

So deactivateFocus updates the state of the component, but it doesn't change focus.

You need to call blur yourself. For example like this:

document.activeElement.blur()
x00
  • 13,643
  • 3
  • 16
  • 40
  • but, if I do that on input element I get blur is not a function – Leff Jun 04 '20 at 20:30
  • That's because input "element" is `MDCTextField` and not a **DOM**-element. You should either use `input.root_` ... but it's `protected`, or `document.querySelector(".mdc-text-field").blur()`. But as there can be only one focused element `document.activeElement` - is more than enough. And as I see you've already changed *codesandbox* with `document.activeElement.blur()` and it works, if I don't miss something. – x00 Jun 05 '20 at 07:45