2

I want to trigger the same effect than when pressing the tab key on an element that has the focus. Is there any way of doing this? I am trying to make the focus jump to the next element.

Thanks!

(jQuery is an option)

John
  • 1
  • 13
  • 98
  • 177
DanC
  • 8,595
  • 9
  • 42
  • 64
  • Possible duplicate of http://stackoverflow.com/questions/1803338/simulate-the-tab-key-function-in-javascript – Stephen P Jun 18 '10 at 21:51
  • DanC, have you found a solution for the issue? I have the same task. Stephen P, this is not a duplicate, there are situations when it's too hard to find the next active element on a page that should be focused. – whitered Dec 22 '10 at 09:19
  • Stephen P, no, I didn't find an answer. I restructured my code so that it would more or less do the job, but I couldn't simulate the effect of pressing the tab key. – DanC Dec 22 '10 at 13:59
  • @whitered: added a new answer that might help you. – Joel Purra Feb 17 '12 at 11:16

2 Answers2

1

Something like this (with jQuery):

    <!DOCTYPE html>

    <html lang="en">

        <head>

            <title>LOL Focus!</title>

            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>

        </head>

        <form>
          <input class="focusable" type="text" value="lol"/>
          <input class="focusable" type="text" value="lol" />
          <input class="focusable" type="text" value="lol" />
          <input class="focusable" type="text" value="lol" />
          <input class="focusable" type="text" value="lol" />
          <input class="focusable" type="text" value="lol" />                 
        </form> 

        <input type="button" id="trigger_button" value="lol" />

        <script type="text/javascript">
        $(function() {

          var focusable = $('.focusable'),
              last_element_index = focusable.length - 1,
              current_index;

          focusable.each(function(i) {
            $(this).click(function() {
              current_index = i;
            })
          });

           $('#trigger_button').click(function() {
             current_index = (should_reset_current_index()) ? 0 : current_index + 1;
             focusable[current_index].focus();
           });

           function should_reset_current_index() {
             return (typeof(current_index) === 'undefined') || (current_index == last_element_index)
           }

        });
      </script>

    </html>
patrick
  • 9,290
  • 13
  • 61
  • 112
0

Needed to emulate the tab functionality a while ago, and now I've released it as a library that uses .

EmulateTab: A jQuery plugin to emulate tabbing between elements on a page.

You can see how it works in the demo.

if (myTextHasBeenFilledWithText) {
  // Tab to the next input after #my-text-input
  $("#my-text-input").emulateTab();
}
Joel Purra
  • 24,294
  • 8
  • 60
  • 60