HTML onfocus event Attribute
Example
First name: <input type="text" id="fname" onfocus="myFunction(this.id)"><br>
Last name: <input type="text" id="lname" onfocus="this.style.background='yellow'">
<script>
function myFunction(x) {
document.getElementById(x).style.background = "yellow";
}
</script>
Meaning
The onfocus attribute specifies that an element has received focus; namely, it has been selected for manipulation or data entry.
Standard Syntax
<element onfocus="script">
Browser Support
Status
Attribute Values
Value | Description |
---|---|
script | Specifies the script to be run on onfocus |
Technical Details
Supported HTML elements:
All HTML elements, EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>
More Example
Example
<input onblur="myBlur()" onfocus="myFocus()" id="demo" type="text" placeholder="Try to focus me!" />
<script>
let x = document.getElementById("demo");
function myBlur(){
x.style.background = "red";
}
function myFocus(){
x.style.background = "green";
}
</script>