JavaScript - focus and focusin differences

0 points
Created by:

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>
    <div id="my-div">
      <p>Click on the input to set focus.</p>
      <input type="text" />
      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.');

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.

❤️💻 🙂