2

What i want to illustrate, is what i want. The text transforms into an input field when the user clicks on it. But it will be the best if the cursor will be there on click. How to earn it?

const input = () => {
  const field = document.querySelector('input');
  document.querySelector('p').style.display = 'none';
  field.style.display = 'block'
}
input{
  display: none
}
<p id='target' onClick='input()'>Click</p>
<input
  type='text' 
  value='type'
  name='name' 
/> 
Gergő Horváth
  • 3,195
  • 4
  • 28
  • 64

2 Answers2

4

No, you can't move the cursor using JavaScript but what you can do is focus the element using HTMLElement.focus(), so typing on the keyboard will result in input in the field:

const input = () => {
  const field = document.querySelector('input');
  document.querySelector('p').style.display = 'none';
  field.style.display = 'block'
  field.focus() // focus the element
}
input{
  display: none
}
<p id='target' onClick='input()'>Click</p>
<input
  type='text' 
  value='type'
  name='name' 
/> 
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
3

The HTMLElement.focus() method sets focus on the specified element, if it can be focused.

const input = () => {
  const field = document.querySelector('input');
  document.querySelector('p').style.display = 'none';
  field.style.display = 'block';
  field.focus();
}
input{
  display: none
}
<p id='target' onClick='input()'>Click</p>
<input
  type='text' 
  value='type'
  name='name' 
/> 
Mamun
  • 66,969
  • 9
  • 47
  • 59