1

I'm trying to determine why something like this doesn't work:

$('a').focus( function() {
  $(this).click(); 
});

Background:

I'm trying to create a form in which tabbing to various elements (e.g. textboxes, etc.) will trigger links to anchors in a div, so that relevant text is scrolled into view as the form is being filled out.

Is there a better way to do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Brian Olpin
  • 87
  • 1
  • 9
  • I think this is a security policy, no? This is a good resource http://stackoverflow.com/questions/1694595/can-i-call-jquery-click-to-follow-an-a-link-if-i-havent-bound-an-event-hand – CambridgeMike May 15 '12 at 18:45
  • Have you looked at the jQuery plugin ScrollTo? – blu May 15 '12 at 18:53

1 Answers1

0
 $('yourInput').on('focus', function(){
      $('yourAnchor').trigger('click');
 });

should work just fine, however you are likely to loose focus on the input field as the new element has been 'clicked'. I would recommend using the jQuery scrollTo plugin instead. That would enable you to do something like this:

 $('yourInput').on('focus', function(){
       $('messageArea').scrollTo('yourAnchor');
 });

This was scrolling occurs in a nice animated fashion and without triggering browser events.

Part of the reason the code you posted may be failing is that, 1. anchors do not always have a focus event, 2. clicking it right after focusing may be redundant and not causing the change you are looking for.

Fresheyeball
  • 29,567
  • 20
  • 102
  • 164