The other day, I was trying to perform some animation when the input field gets focus . Let me be specific. I have a text input field and when it gets focus, I want to move the input field towards the left as shown in figure. After the animation is complete, I want to run some validation logic once the user submits the form.
<style>
.normal{margin-left: 50px;}
.animate{margin-left: 0px;-webkit-transition: all 0.3s ease-out; }
</style>
<div id="sb" class="normal">
<form>
<input id="q" name="q" type="text" value="flowers" onfocus="OnFocusEventHandler(event);"/>
</form>
</div>
function OnFocusEventHandler(e)
{
var ele = $("sb");
ele.className = "animate";
}
OnFocusEventHandler changed the css class of the input field container which essentially performed the animation. This worked so far. As I mentioned in one of my previous blog post, I hooked up the validation logic to keydown event of the input field. But to my surprise, when the user tapped on "return" key on the keyboard, the keydown event handler never got fired ! Browser also didn't fire submit event on the form.
To debug the problem, I tried animating the input field by clicking on a button, putting focus on input field manually by tapping on it and then submitting the form by hitting the "return" key. This time everything worked fine - keydown event handler got called and the validation logic ran just fine. I also tried attaching the animation logic to mousedown / touchend events of the field but met with no success. With some more experimentation, I found that if I move the input element as soon as it gets focus (and at the same time browser brings up the virtual keyboard), the keyboard events are not properly attached to the input field.
Then I tried the obvious thing - I waited for sometime after onfocus event to begin the animation by using Window.setTimeout. And that did the trick. I set the delay of 500 ms (100, 200 ms etc didn't solve the problem) before I started the animation. Essentially I had to wait for the keyboard to become visible completely before I can start the animation.
function OnFocusEventHandler(e)
{
window.setTimeout(function()
{
var ele = $("sb");
ele.className = "animate";
}, 500);
}
I was hoping that a very simple thing like this would just work out of the box. But it didn't. Sad Web Developer :(.
No comments:
Post a Comment