0

I am using a popup container in HTML, that contains one label (input) option for text, and a few buttons. I want the user to be able to start typing into the input field when the popup opens (which is triggered by a keyboard shortcut I am using), not necessarily having to click on it. how can i do so?

This is my HTML code snippet of the Popup menu:

<div id="popupContainer">
  <div id="popupContent">
    <label for="AnnotateLabel">Label: <input type="text" id="AnnotateLabel" autocomplete="off" required></label><br>
    <button id="saveButton">Save</button>
    <button id="deleteButton">Delete</button><br><br>
    <!--<button id="closeButton">Close</button><br>-->
    <label for="loopRegion">Loop Region: <input type="checkbox" id="loopRegion" checked> </label><br>
    <!--<button id="playPopup">Play</button>-->
    <span>Playback Rate: </span>
    <button class="play-quarterx" data-action="play-quarterx">0.25x</button>
    <button class="play-halfx" data-action="play-halfx">0.5x</button>
    <button class="play-1x" data-action="play-1x">1.0x</button>
  </div>
</div>

5
  • In the script which opens the menu do document.querySelector('#AnnotateLabel').focus();. Commented Feb 29, 2024 at 6:41
  • Depends on how you open the dialog / populate the dialog etc, but once the dialog is visible, use focus() Commented Feb 29, 2024 at 6:42
  • Thanks @Teemu , that worked. I wasn't calling the focus() method inside the popup code i wrote. Thank you so much! Commented Feb 29, 2024 at 6:44
  • However Commented Feb 29, 2024 at 7:24
  • It might be confusing for some that the linked duplicate answer is all about React, while this question is about native HTML/JavaScript. Commented Feb 29, 2024 at 8:03

1 Answer 1

2

There are two ways.

autofocus HTML attribute

HTML has support for this out of the box, without the need of JavaScript. You'll probably need to wrap your code in <dialog> element, and then use autofocus attribute like this:

<input type="text" id="AnnotateLabel" autocomplete="off" required autofocus>

Use HTMLElement.focus method

JavaScript can also focus an element. Read more here. After showing the popup, make this call.

document.getElementById('AnnotateLabel').focus();
Sign up to request clarification or add additional context in comments.

1 Comment

Nice one. TIL autofocus. Available since end 2019 😲

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.