The JavaScript onfocus event will occur when an element (most of the time an input) gets the user’s focus. This occurs when either the user mouse clicks onto the element, or tabs onto it using the keyboard.
We can add a function call to the onfocus event and run some code when a user’s focus enters the input.
Let’s say we have the following HTML:
To highlight the input field when the user clicks on it, we can add an onfocus event to the input field.
Once the user clicks on the input field, the onfocus event will be triggered and will launch the changeBackground() function where we can change its background color.
function changeBackground(){
document.getElementById("fname").style.backgroundColor = "green";
};
This can also be done using the jQuery focus() method.
An Interactive Example of Using JavaScript with the onfocus Event
Below we will set up a simple form with a name field and a submit button.
Here is the HTML code:
When the user clicks or tabs into the name field, we will change the background color to light blue. When they click away, we will use the onfocusout event to run the resetBackground() function where we can reset the background color.
In the resetBackground() function, we will change the background color of the input field by using the backgroundColor property.
Here are the code JavaScript functions:
function changeBackground(){
document.getElementById("fname").style.backgroundColor = "#d1e2f3";
};
function resetBackground(){
document.getElementById("fname").style.backgroundColor = "#fff";
};
The final code and output for this example of using JavaScript with the onfocus event is below:
Code Output:
Full Code:
<script>
function changeBackground(){
document.getElementById("fname").style.backgroundColor = "#d1e2f3";
};
function resetBackground(){
document.getElementById("fname").style.backgroundColor = "#fff";
};
</script>
Hopefully this article has been useful to help you understand how to use JavaScript with the onfocus event.