简体   繁体   中英

How to add event listener to div without tabindex=0?

I have something like this control:

在此处输入图片说明

I need to track focus on any element inside this control. If I focus input or If I focus (click) calendar icon, I want to know that focus performed.

My idea is to add click listener on wrapper of input + calendar trigger. It is some div.

Out of the box I can't add focus listener to the div. To achieve this I need to add tabindex=0 to this div. This method will work, but it has one minus.

For example, I have form with many controls. Example code is below:

<div class="container">
  <input onfocus="onFocus()" />
  <div tabindex="0" onfocus="onFocus()">some div</div>
  <div tabindex="0" onfocus="onFocus(event.target)">
    <input onfocus="onFocus()" />
  </div>
  <input onfocus="onFocus()" />
</div>

When I focus first input and start looping through TAB key I want this behavior: focus calendar icon, focus next input, focus next calendar icon etc. But with tabindex=0 I break this behaviour. You can check it in this pen . You can see this broken behaviour after some div block.

Well, I have another option to add listener specifically for input and calendar icon (or any other icon). The problem is I have dynamic amount of icons on each field. And I have to add focus listener for each. Much simpler for me (and another developers) is the way when I have only one focus listener on the top (as I think).

Is it somehow possible to add ability to add focus listener to the div without breaking focus loop (like I shown on the codepen example).

Use element.addEventListener('focusin', handler) . focus and blur don't bubble, focusin and focusout do.

 document.querySelector('.container') .addEventListener('focusin', function(event) { console.log(event.target) }) 
 <div class="container"> <input name="a" /> <div contenteditable="true">some div</div> <div> <input name="b" /> </div> <input name="c"/> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM