Languages
[Edit]
EN

JavaScript - onfocus event example

0 points
Created by:
Dirask Community
6240

In this article, we would like to show you onfocus event example in JavaScript.

Quick solution:

var myElement = document.querySelector('#my-element');

myElement.addEventListener('focus', function() {
    console.log('onfocus event occurred.');
});

or:

<input type="text" onfocus="handleFocus()">

or:

var myElement = document.querySelector('#my-element');

myElement.onfocus = function() {
    console.log('onfocus event occurred.');
};

 

Practical examples

There are three common ways how to use onfocus event:

  • with event listener,
  • with element┬áattribute,
  • with element property.

1. Event listener based example

In this section, we want to show how to use onfocus event on input element via event listener mechanism.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <p>Click on the input field to set focus.</p>
    <input type="text" id="my-input">
    <script>
      var myInput = document.querySelector('#my-input');

      myInput.addEventListener('focus', function() {
        console.log('onfocus event occurred.');
      });
    </script>
  </body>
</html>

2. Attribute based example

In this section, we want to show how to use onfocus event on input element via attribute.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <p>Click on the input field to set focus.</p>
    <input type="text" onfocus="handleFocus()">
    <script>
      function handleFocus(){
        console.log('onfocus event occurred.');
      }
    </script>
  </body>
</html>

3. Property based example

In this section, we want to show how to use onfocus event on input element via property.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <body>
    <p>Click on the input field to set focus.</p>
    <input type="text" id="my-input">
    <script>
      var myInput = document.querySelector('#my-input');

      myInput.onfocus = function() {
        console.log('onfocus event occurred.');
      };
    </script>
  </body>
</html>

JavaScript - events

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join