How to Check If Element Has Focused Child Using JavaScript

Know what element is currently focused using focus()

To achieve this you can use a delegated event handler. It will listen for the focus event on all child elements.

Note that this example is listening for the event on any form control, but that selector can be amended to target what is required in your specific use case.

$(document).on('focus', ':input', function() {  console.log(this.id);});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><input type="text" id="foo" /><input type="text" id="bar" /><input type="text" id="fizz" /><input type="text" id="buzz" />

checking all children of a submenu to see if any element has focus in jquery, using :focus selector

Try this

$("#submenu").mouseleave(function () {
//This will check if any child of submenu has focus. If no then hideLinks
if ($(this).children(":focus").length == 0){
hideLinks();
}
});

How do I shadow a div if it's child element is focused?

Pure CSS solution

#main {
padding: 30px;
margin: 31px;
}

#main:focus-within {
box-shadow: 0px 0px 10px red;
}
<div id="main">
<input type="text" id="input" placeholder="focus me!">
</div>

How to check if any form element inside a fieldset has focus

Don't you just need to wait for the focus on the new element to happen? Like this:

const fieldsets = [...document.querySelectorAll('fieldset')]
for (const fieldset of fieldsets) { fieldset.addEventListener('focusout', (e) => { let ct = e.currentTarget; setTimeout(() => { let focussedElements = ct.querySelectorAll(':focus'); if (focussedElements.length === 0) { console.log(`no element inside fieldset #${ct.id} has focus`) } else if (focussedElements.length > 0) { console.log(`element ${focussedElements[0]} inside fieldset #${ct.id} has focus`) } }, 10) })}
<fieldset id="fs1">  <legend>Fieldset 1</legend>  <input type="text">  <input type="text"></fieldset>
<fieldset id="fs2"> <legend>Fieldset 2</legend> <input type="text"> <select> <option>1</option> <option>2</option> </select></fieldset>

Detecting when a child outside of element gets focus

Because the blur event fires before the focus event fires, you should set a timeout in the blur event, and cancel it in the focus event.

(function () {

var bar = $("#bar");
var timeout;

bar.find("a").on("focus", function(){
clearTimeout(timeout);

if(bar.css("margin-top") == "-50px"){
bar.animate({ marginTop: 0 }, 250);
}
});

bar.find("a").on("blur", function(){
timeout = setTimeout(function () {
// If no links inside #bar have focus now:
bar.animate({ marginTop: -50 }, 250);
}, 1);
});

}());


Related Topics



Leave a reply



Submit