Some thoughts are that the ELEMENT_ID.focus() is inside divs that are hidden at certain times.
This should be an easy problem to solve -- but I'm struggling :(
***code works fine -- the text field isn't being focused on upon page loading up.
STEP1 [SOLVED] JAVASCRIPT:
$("#goal-input").focus(); $('#goal-input').keypress(function(event){ var keycode = (event.keyCode ? event.keyCode : event.which); if(keycode == '13') { etc, etc, etc }
HTML
<input type="text" id="goal-input" name="goal" />
[STEP2] JAVASCRIPT:
if (goal) { step1.fadeOut('fast', function() { step1.hide(); step2.fadeIn('fast'); etc, etc
HTML:
<div id="step-2"> <div class="notifications"> </div> <input type="text" id="name" name="name" placeholder="Name" /> <script type="text/javascript"> $(function(){ $("#name").focus(); }); </script>
Why doesn't step 2 work? :(
The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it). The focus() method triggers the focus event, or attaches a function to run when a focus event occurs. Tip: This method is often used together with the blur() method.
If jQuery UI is not loaded, calling the . focus() method may not fail directly, as the method still exists. However, the expected behavior will not occur. This method is deprecated.
focus() on elements that are visible. To run an element's focus event handlers without setting focus to the element, use . triggerHandler( "focus" ) instead of . focus() .
The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button. Here selector is the selected element. Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.
I had problems triggering focus on an element (a form input) that was transitioning into the page. I found it was fixable by invoking the focus event from inside a setTimeout with no delay on it. As I understand it (from, eg. this answer), this delays the function until the current execution queue finishes, so in this case it delays the focus event until the transition has completed.
setTimeout(function(){ $('#goal-input').focus(); });
You need to either put the code below the HTML or load if using the document load event:
<input type="text" id="goal-input" name="goal" /> <script type="text/javascript"> $(function(){ $("#goal-input").focus(); }); </script>
Update:
Switching divs doesn't trigger the document load event since everything already have been loaded. You need to focus it when you switch div:
if (goal) { step1.fadeOut('fast', function() { step1.hide(); step2.fadeIn('fast', function() { $("#name").focus(); }); }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With