Modermo Modermo - 1 month ago 17
jQuery Question

Input won't focus when element opens

Trying to get an input to focus when the parent container has the class open.

Code I have so far is:

$("#search-trigger").click(function(){
$("input").focus();
});


Which, only works oddly when the element begins to close. So, I changed it to:

$("#search-trigger").click(function(){
if(("#target-2").hasClass("open")){
$("input").focus();
}else{
$("input").blur();}
});


Which doesn't work at all. Any ideas?

Codepen here

Answer

I updated your CodePen.

You have an animation going on...
I didn't checked how it is achieved closely, since an external lib (TweenMax) is doing it.

But, seeing the animation, I thought about delay.
And this is my answer.

You can't focus an element that has display setted to none.
This display is setted to block or inline-block by your animation somewhere...

I found that a 10ms delay was enought in this case.
And just to be sure we select the right input, because even if there is only one in that example... Your site will have more for sure.

I specified it to be a children of a sibling of the clicked element.

Here is the relevant code:

// This is the code for the input focus
$("#search-trigger").click(function(){
    var searchInput = $(this).siblings().find("input");
    setTimeout(function(){
        searchInput.focus();
    },10);
});