Languages
[Edit]
EN

JavaScript - focus and focusin differences

0 points
Created by:
Vanessa-Drake
718

In this article, we would like to show you the differences between focus and focusin events in JavaScript.

The difference between focus and focusin:

  • focus - doesn't bubble, can't be delegated,
  • focusin -  bubbles to the parent element, can be delegated.

Practical example

In this example, we will try to add two event listeners to the my-div element, but only focusin will occur when we set focus on the <input> element inside.

// ONLINE-RUNNER:browser;

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

      // this will not work, focus event doesn't bubble
	  div.addEventListener('focus', handleOnfocus, false);

      // this works fine when the input is focused, as the focusin event bubbles
      div.addEventListener('focusin', handleOnfocusin, false);

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

      function handleOnfocusin() {
        console.log('onfocusin event occurred.');
      }
    </script>
  </body>
</html>

 

Alternative titles

  1. JavaScript - onfocus and onfocusin differences
  2. JavaScript - onfocus vs onfocusin
  3. JavaScript - focus vs focusin
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - DOM Node - problems & solutions

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