Search code examples
javascripthtmladdeventlistener

Trigger event when any child is focused in JS


Consider the following HTML:

<div id="parent">
  <div class="line">
    <span class ="word">This </span>
        <span class ="word">is  </span>
        <span class ="word">a  </span>
        <span class ="word">line. </span>  
    </div>
    <div class="line">
    <span class ="word">This </span>
        <span class ="word">is  </span>
        <span class ="word">another  </span>
        <span class ="word">line. </span>  
    </div>
</div>

<textarea id="textarea"></textarea>

The content of the parent is dynamic (it may change during runtime).

I would like to report the focus of parent or any descendant the textarea. For example, if the user click on the parent, the focus is set on the textarea.

I did the following, but it does not work:

let parent = document.getElementById("parent");
let textarea = document.getElementById("textarea");

parent.addEventListener("focus", () => { 
    textarea.focus();
})

Any idea is welcome. Here is a JSFiddle: https://jsfiddle.net/Imabot/6y4d931b/


Solution

  • Make the parent DIV focusable:

    <div id="parent" tabindex="-1">
    

    Use tabindex="-1" for the click only and tabindex="0" if you want to get the event when you navigate with a keyboard.

    Also please use embedded code snippets here, that way you can get them right, without typos for example.

    let parent = document.getElementById("parent");
    let textarea = document.getElementById("textarea");
    
    parent.addEventListener("focus", () => { // you have a type here, should be addEventListener
        console.log ("focus");
        textarea.focus();
    });
    <div id="parent" tabindex="-1">
      <div class="line">
        <span class ="word">This </span>
            <span class ="word">is  </span>
            <span class ="word">a  </span>
            <span class ="word">line. </span>  
        </div>
        <div class="line">
        <span class ="word">This </span>
            <span class ="word">is  </span>   
            <span class ="word">another  </span>
            <span class ="word">line. </span>  
        </div>
    </div>
    
    <textarea id="textarea"></textarea>