I want to perform a function after a div element has left focus.
I'm using tabIndex and onBlur function inside the div. And its working fine when i manually put focus by clicking on any of the elements inside the div. But by default when no item is clicked inside the div, its not working.
My component is a Functional Component & the div is rendered dynamically so also I'm unable to set focus using useRef.
const renderHeaderCell = (header, headerKey) => {
return (
<div className="DataTable__header-cell-wrapper">
{filterable ? (
<IconButton onClick={() => toggleFilterPanel(headerKey)}>
<i className="material-icons">filter_list</i>
</IconButton>
) : null}
{activeFilterHeader === headerKey ? (
<div
tabIndex={0}
onFocus={e => {
console.log("DIV", "focus");
}}
onBlur={e => {
console.log("DIV", "blur");
}}
style={{ border: "1px solid blue" }}
>
DIV container
<input
type="text"
onFocus={e => {
console.log("input", "focus");
}}
onBlur={e => {
e.stopPropagation();
console.log("input", "blur");
}}
placeholder="Inside Textbox"
/>
Click outside
</div>
) : null}
{sortedByColumn === headerKey ? renderSortIcon() : null}
</div>
);
};
Code after i click the icon to show the DIV
const toggleFilterPanel = headerKey => {
if (activeFilterHeader === headerKey) {
setActiveFilterHeader("");
} else {
setActiveFilterHeader(headerKey);
setUniqueItemsForFilter(getUniqueItemsForFilter(rows, headerKey));
}
};
Code after onBlur is called
const onBlur = () => {
console.log("Blured");
};
So how shall i make onBlur to work on a div element?
Following image shows current focus
onBlur
andonFocus
only on focusable elements. The reason is that safari ignoring tabIndex by default. So you can't relay on that behaviour if you want cross browser support – Arseniy-II<div tabIndex={0} onBlur={onBlur}>
will not be focusable.onBlur
andonFocus
on such elements will not work on safari too. – Arseniy-IItabindex
for having a tab order, but it's not ignoringtabindex="0"
for enabling focus – keultabindex="0"
.<div tabIndex={1}>
will be focusable andonBlur
andonFocus
will work. But there is another problem<button>
is not focusable element on safari. And<button tabindex="0">
will be not focusable too. – Arseniy-II