JavaScript onfocus Event Example

Updated on     Kisan Patel

If we want to execute a javascript function on focus of the element, we need to use javascript onfocus event.

<!-- HTML -->
Name: <input type="text" name="txtName" id="txtName" onfocus="TestFunction(this.id)" />

<-- Javascript -->
<script type="text/javascript">
function TestFunction(id) {
   document.getElementById(id).style.background = "#FFF200";
}
</script>

Output of the above program…

javascript-onfocus-event

In the above code snippet, we have a textbox with onfocus event. When we focus (place cursor) on the textbox, TestFunction() function executes that receives the id of the textbox that causes this event to execute. In this function, we are finding the texbox using javascript getElementById method and setting its background color to “#FFF200”.

See the Pen xGebRN by Kisan (@pka246) on CodePen.


JavaScript

Leave a Reply