I want to know when any of the input fields lose focus i.e. when the cursor is no longer present in the input field. The condition is new input fields can be created even after the page load.
Input fields include: textarea and divs with contenteditable: true.
To give you more details I’m building a chrome extension so adding onblur=func() attribute to input fields is out of the scope.
>Solution :
Reply generated with ChatGPT:
One way to accomplish this is to use the addEventListener() method to attach a blur event to the document object. This event will be triggered whenever any input element on the page loses focus.
First, you can create a function that will be called whenever a blur event is triggered. This function should check if the element that triggered the event is an input element (i.e. a textarea or a div with contenteditable set to true). If it is, then you can do whatever processing you need to do in response to the input field losing focus.
Here is an example of how this might look:
// Function to be called when an input field loses focus
function handleBlurEvent(event) {
// Check if the element that triggered the event is an input field
if (event.target.matches('textarea, [contenteditable="true"]')) {
// Do something in response to the input field losing focus
}
}
// Attach the blur event to the document object
document.addEventListener('blur', handleBlurEvent, true);
This approach has the advantage of being efficient and easy to implement, but it only works for blur events (i.e. when the input field loses focus). If you want to also handle focusout events (i.e. when the input field loses focus and the focus moves to a different element), you can use a similar approach but attach the focusout event to the document object instead.
Here is an example of how this might look:
// Function to be called when an input field loses focus
function handleFocusoutEvent(event) {
// Check if the element that triggered the event is an input field
if (event.target.matches('textarea, [contenteditable="true"]')) {
// Do something in response to the input field losing focus
}
}
// Attach the focusout event to the document object
document.addEventListener('focusout', handleFocusoutEvent, true);
This approach will allow you to handle both blur and focusout events for all input fields, including any that are created after the page has loaded.