js focus input code example

Example 1: set focus javascript

document.getElementById("ThingToSetFocusOn").focus();

Example 2: focus js

focusMethod = function getFocus() {          
  document.getElementById("myButton").focus();
}

Example 3: focus js

focusMethod = function getFocus() {           
  document.getElementById("myTextField").focus();
}

Example 4: js focus event

const form = document.getElementById('form');

form.addEventListener('focus', (event) => {
  event.target.style.background = 'pink';    
}, true);

form.addEventListener('blur', (event) => {
  event.target.style.background = '';    
}, true);

Example 5: focus js

<input type="text" id="myTextField" value="Text field.">
<p></p>
<button type="button" onclick="focusMethod()">Click me to focus on the text field!</button>