Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
How to automatically set the cursor to an input tag

I have an input tag and what im trying to do is listen for the / key press and automatically set the cursor to the input tag to start typing on it. Google already has this and will automatically go to the search bar when you press the / key. How can I achive this. Any help is appreciated. Thanks in advance.

document.onkeypress = function(evt) {
  evt = evt || window.event;
  var charCode = evt.keyCode || evt.which;
  var charStr = String.fromCharCode(charCode);
  if (charStr == '/') {
    //set cursor to input bar
  }
};
#inputBar {
  position: absolute;
  top: 2%;
  left: 3%;
}
<input id="inputBar" />

UPDATE: as suggested the focus method will do it but the / charater will also get registerd on the input bar. How should i handle this? Sholud i make a separate function that removes the / char if detected within < 10ms of the / keypress. Or any other better ideas?

document.onkeypress = function(evt) {
  evt = evt || window.event;
  var charCode = evt.keyCode || evt.which;
  var charStr = String.fromCharCode(charCode);
  if (charStr == '/') {
    //set cursor to input bar
    document.getElementById("inputBar").focus();
  }
};
<input id="inputBar" />

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This should handle all your requirements. I'm using keydown instead of keypress because the latter is deprecated.

document.addEventListener('keydown', function (e) {
  const inputBar = document.getElementById("inputBar")
  const isFocused = inputBar === document.activeElement
  if (isFocused) return
  if (e.code == 'Slash') {
    e.preventDefault()
    inputBar.focus()
  };
});
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to use a combination of preventDefault to stop what the event was going to do, and focus, to focus on the input. You also need a way to identify the the body element was clicked for which you need nodeName so you can still use the input element.

Your code (note: which uses the now-deprecated keycode listener) updated to use these methods:

var input = document.getElementById('inputBar');

document.onkeypress = function(evt) {
  evt = evt || window.event;
  var nodeName = evt.target.nodeName;
  var charCode = evt.keyCode || evt.which;
  var charStr = String.fromCharCode(charCode);
  if (nodeName === 'BODY' && charStr == '/') {
    evt.preventDefault();
    input.focus();
  }
};
<input id="inputBar" />

Some more modern code that uses code (thanks for Meron Ogbai for pointing out that keypress is also deprecated).

const input = document.querySelector('#inputBar');

document.addEventListener('keydown', handleKey, false);

function handleKey(e) {
  const { code } = e;
  const { nodeName } = e.target;
  if (nodeName === 'BODY') {
    e.preventDefault();
    if (code === 'Slash') input.focus();
  }
}
<input id="inputBar" />

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda