How to focus an input in a modal once opened? #491
Replies: 7 comments 8 replies
-
Hey @sebszocinski, have you got a code snippet for your modal? There's a couple of ways you could do this, but it's easier if I can see your code so I can tailor it to your use case. |
Beta Was this translation helpful? Give feedback.
-
Hi @sebszocinski you have to wait until Alpine updates the dom then focus in your input. To do so just make a new task in JS Stack by setTimeout: $nextTick(() => {
setTimeout(() => {
document.querySelector('input').focus();
}); // has a default time value of 0
}); |
Beta Was this translation helpful? Give feedback.
-
Thanks for the help guys! I had previously tried $nextTick but didn't have any luck... I might have missed something. I tried again with your example @ahmedkandel and it worked but I had to set a timeout of at least 3ms (kind of odd). I have a transition but that is set to 300ms, so I initially thought i'd need a timeout for at least 300ms but it turns out 3ms is enough for it to kick in... anything lower and it doesn't focus. I might just set it to 300 anyway to be safe.... I do wish there was a better way with less code. Examples of my code : Trigger:
Modal:
|
Beta Was this translation helpful? Give feedback.
-
Inside The timing issue here is that
@sebszocinski in your case you will need a few microseconds as the promise will resolve immediately but you have to wait for |
Beta Was this translation helpful? Give feedback.
-
I think those cases lead us to the conclusion that $nextTick may need some improvements. I will dig more and try to figure out a solution that respects also transitions without asking the user to implement setTimeout inside $nextTick. Maybe I will create a PR to make $nextTick works that way the user expects. Note: one of the possible solutions is to use "double requestanimationframe" for $nextTick |
Beta Was this translation helpful? Give feedback.
-
PR created #502 Codepen before PR https://codepen.io/tomorrowsystem/pen/yLYQxNp |
Beta Was this translation helpful? Give feedback.
-
This almost seems like something Alpine should handle (but I'm not sure). Like if a new dom node is added and has Thoughts? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I can't seem to work out how to do this, I think its a timing issue.
Beta Was this translation helpful? Give feedback.
All reactions