Search code examples
mdc-components

MDC web components - Deactivating focus from textfield not working


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?


Solution

  • 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()