Matheus Moraes
Matheus Moraes

Reputation: 17

How can I make clicks trigger the "blur" and "focus" event of an absolute element?

I'm trying to trigger both focus and blur events on an absolute positioned element based on clicks like every normal element, so when the dropdown menu loses focus, it collapses itself, however, it doesn't react in any way. When I manually do it through

event=new Event('blur/focus') //any of the two
absoluteDiv.dispatchEvent(event)

It works.

Html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        #absoluteDiv{
            background-color:black;
            position:absolute;
            top:0px;
            right:0px;
            z-index:10;
            pointer-events:all;
            color: white;
        }
    </style>
    <script src='divProblem.js' defer></script>
</head>
<body>
    <div>I'm just a regular div</div>
    <div id='absoluteDiv'>I'm an absolute div</div>
</body>
</html>

Javascript:

div=document.getElementById('absoluteDiv')


div.addEventListener('blur', (e)=>{
    console.log('I was blurred')
})

div.addEventListener('focus', (e)=>{
    console.log('I was focused')
})

I'm sure that although not ideal, I can do some workaround adding a click event listener to the whole body, but even in this case, I'm at least curious why the absolute element works this way. Why it's focus and blur events are not triggered with clicks? Even with the CSS property pointer-events:all. I cannot find this searching in the web.

Upvotes: 0

Views: 121

Answers (1)

nikk
nikk

Reputation: 466

Non-interactive elements aren't focusable by default, which is why your div isn't emitting those events. You can make it focusable by adding the tabindex attribute:

<div tabindex="0">...</div>

The value determines the element's index in the selection cycle controlled by the "Tab" key.

Upvotes: 0

Related Questions