The onfocus attribute is triggered when an element gains focus.
onfocus is commonly used for <input>, <select> and <a>.
Tip: The onfocus attribute is the opposite of the onblur attribute.
Note: The onfocus attribute does not apply to the following elements: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> or <title>.
ExampleFunction triggered when the input field gets focus. This function changes the background color of the input field
<script>function setStyle(x){document.getElementById(x).style.background=yellow;}</script></head><body> <p>The function is triggered when the input field gains focus. This function changes the background color of the input field. </p> First name: <input type=text id=fname onfocus=setStyle(this.id)><br>Last name: <input type=text id=lname onfocus=setStyle(this.id)> </body > HTML onblur event attribute Definition and usageThe onblur attribute is triggered when the element loses focus.
onblur is often used in form validation code (such as when the user leaves a form field).
ExampleValidate an input field when the user leaves it:
<script>function upperCase(){var x=document.getElementById(fname).valuedocument.getElementById(fname).value=x.toUpperCase()}</script></head><body> <p>Please enter your name, then move focus outside the field:</p> Please enter your name (English characters): <input type=text name=fname id=fname onblur=upperCase()> </body>The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.