The HTML DOM onfocus event occurs when an element gets focused. The onfocus event is mostly used with <input>, <select>, and <a>. The onfocus event is the opposite of the onblur event.
Syntax:
<element onfocus="myScript">
object.onfocus = function(){myScript};
- In JavaScript, using the addEventListener() method:
object.addEventListener("focus", myScript);
Note: The onfocus event is different from the onfocusin event because the onfocus event does not bubble.
Example 1: This example explains the onfocus event in the HTML.
html
< center >
< h1 style = "color:green" >
GeeksforGeeks
</ h1 >
< h2 >
HTML DOM onfocus Event
</ h2 >
< br > Name:
< input type = "text" onfocus = "geekfun(this)" >
< script >
function geekfun(gfg) {
gfg.style.background = "green";
}
</ script >
</ center >
|
Output:
Example 2: In this example, we will learn about the onfocus event by using Javascript.
html
< center >
< h1 style = "color:green" >
GeeksforGeeks
</ h1 >
< h2 >HTML DOM onfocus Event</ h2 >
< br > Name:
< input type = "text" id = "fname" >
< script >
document.getElementById(
"fname").onfocus = function() {
geekfun()
};
function geekfun() {
document.getElementById(
"fname").style.backgroundColor =
"red";
}
</ script >
</ center >
|
Output:
Example 3: In this example, we will learn the onfocus event by the addEventListener() method.
html
< center >
< h1 style = "color:green" >
GeeksforGeeks
</ h1 >
< h2 >HTML DOM onfocus Event</ h2 >
< br > Name:
< input type = "text" id = "fname" >
< script >
document.getElementById(
"fname").addEventListener(
"focus", Geeksfun);
function Geeksfun() {
document.getElementById(
"fname").style.backgroundColor = "green";
}
</ script >
</ center >
|
Output:
We have a complete list of HTML DOM methods, to check those please go through this HTML DOM Object Complete reference article.
The HTML DOM onfocus event support all HTML tag EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, <title>
Supported Browsers: The browsers supported by HTML DOM onfocus Event are listed below:
- Google Chrome
- Internet Explorer
- Firefox
- Apple Safari
- Opera
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Dec, 2022
Like Article
Save Article