T
T
Thomas Jefferson2021-06-21 17:03:11
JavaScript
Thomas Jefferson, 2021-06-21 17:03:11

How to hang focus action on child elements in js?

Hello
, I would like to add a class after the focus is removed from the form, but the focus of the parent does not extend to the child elements, and therefore, after the user enters the input text and clicks on the free part of the site, nothing happens, I would like the focus to work parent and on child elements, i used focusout, blur but nothing worked, does anyone know?

Here is the form

<form action="#">
      <div class="form_block" tabindex="0">
         <input type="text" id="fred">
         <div class="text-arr"></div>
      </div>
</form>


here is js

$('form_block').on("focusout", ()=>{
         $('form_block').addClass('dd')
      })

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2021-06-21
@Seasle

const form = document.querySelector('form');

for (const element of form.elements) {
  const wrapper = element.closest('.form_block');
  if (wrapper !== null) {
    element.addEventListener('blur', (event) => {
      if (!wrapper.contains(event.relatedTarget)) {
        wrapper.classList.add('dd');
      }
    });
  }
}

and tabindex="0"you can remove.

A
Aetae, 2021-06-22
@Aetae

The parameter trueallows you to monitor all "passing by" events.

form.addEventListener('blur', e => console.log('скоро уйдём с элемента', e.target, 'формы', form), true)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question