window.addEventListener('focus', function (e) { } check if e is textbox

← Prev

Let us assume, I have a textbox and other input elements on my web page. I am using windows.addEventListner() to capture focus event. However, how do I check if the focused element is a textbox? Here's a solution.

Example:

<body>
  <p><input type='text' value='' id='txt' placeholder='Set focus here'></p>
  <p><input type='button' value='...'></p>
</body>
<script>
  // Add an event listner to check if the focused element is a textbox.
  window.addEventListener('focus', function (e) {
    if (e.target.tagName === 'INPUT' && e.target.type === 'text') {       
      e.target.style.outline = 'none';  // If its a textbox, set outline to "none".
    }
  }, true);
</script>
Try it

The above code listens for the "focus" event and checks if the focused element is an input box of type text. "e" is the "event". Within the "if" condition it checks if the target element is an "input" of type "text". I have defined two input boxes: one of type "text" and another of type "button". So to be certain, I am checking the "type" within the "if..." condition.

The true parameter in window.addEventListener() is used to specify that the event listener should be executed in the capturing phase, meanaing, focus event is captured at the window level before it reaches the input element.

← Previous