javascripthtmlsimultaneous

why does the same event recognise different activeElements?


If I click a button the activeElement is the button.
If I leave an input box the activeElement is the Window.
If I leave an input box by clicking on a button the activeElement is ... both?
Why does the onfocusout event not register the same activeElement as the button? Is there anyway I can access the click-on-button event from the function call of the inputbox-leave-event?
ie can I ask, "Did you leave me for the lousy button?"

<button  type="button" onclick = "myFunction()">   button   </button><br>
<input   type="text" onfocusout= "myFunction()">  </input>

<script>
function myFunction() { 
  console.log(document.activeElement);
} 
</script> 

Solution

  • The relatedTarget in the event will show you where it's leaving to

    of course, you have to use addEventListener to access the event in the first place

    But I think this demonstrates what you want to see

    it'll definitely tell you

    "Did you leave me for the lousy button?"

    const button = document.querySelector('button')
    const input = document.querySelector('input')
    
    function buttonHandler(e) {
      console.log('button clicked');
    }
    
    function inputHandler(e) {
      console.log('leaving input for', e.relatedTarget?.tagName || 'window');
    }
    input.addEventListener('focusout', inputHandler);
    button.addEventListener('click', buttonHandler);
    <button type="button">   button   </button><br>
    <input type="text"> </input>