In JavaScript, we can set the cursor position very easily using the focus() method.
document.getElementById("someInputField").focus();
We usually will want to set the cursor position to an input field to get the user’s attention to a form.
We can also set the cursor potion right after the page loads. To do this we will use the window object and call a function once it loads. Our function will use the focus() method to highlight the first field in the form below.
So in this example, the input field for label Name should have the cursor in it to start. If it does not, it means you might have clicked somewhere else on the page. Simply refresh the page and look at the name field below.
Here is the HTML code for the example above:
And the JavaScript code:
window.onload = function(){
document.getElementById("fname").focus();
};
Using JavaScript to Set the Cursor Position on a Form
In this example, it will be similar to the example above, only we will set the cursor position to the name field when we click a button this time.
Here is the HTML code:
We will attach an onclick event to the button so that when the user clicks the button, our function will run.
In our function, we will use the focus() method to set the cursor position to be in the name input field.
Here is the JavaScript code for setting the cursor position:
function setCursorPosition(){
document.getElementById("fname1").focus();
};
The final code and output for this example of using JavaScript to set the cursor position on a form is below:
Code Output:
Full Code:
Hopefully this article has been useful to help you understand how to use JavaScript to set cursor position.