JavaScript onfocus Event

You are Here:

JavaScript onfocus Event

The onfocus event occurs when an element gets focus.

Note: Unlike onfocusin event, the onfocus event will NOT bubble, i.e., The element with onfocus event will NOT be affected when its child element gets focus.

onfocus Event as Attribute

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <input type="text" onfocus="myFunction(this)"> <script> function myFunction(x) { x.style.color = "red"; } </script> </body> </html>

Syntax

As Attribute

<element onfocus = "JavaScript">

As Property

object.onfocus = function(){ // code };

Using Event Listener

object.addEventListener("focus" , myScript);

onfocus Event as Property

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Type your Name</p> <input type="text"> <script> var x = document.getElementsByTagName("input")[0]; function myFunction() { x.style.color = "red"; } x.onfocus = myFunction; </script> </body> </html>

Using addEventListener() Method

Note: The addEventListener() method is not supported in Internet Explorer 8 and below.

Example

HTML Online Editor
<!DOCTYPE html> <html> <body> <p>Type your Name</p> <input type="text"> <script> var x = document.getElementsByTagName("input")[0]; function myFunction() { x.style.color = "red"; } x.addEventListener("focus", myFunction); </script> </body> </html>

onfocus vs onfocusin

Check out the difference between onfocus vs onfocusin in javascript.

Reminder

Hi Developers, we almost covered 97% of JavaScript Tutorials with examples for quick and easy learning.

We are working to cover every Single Concept in JavaScript.

Please do google search for:

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author