views:

32

answers:

2

As soon as a page loads, I want the focus to jump to a particular link, so hitting enter will 'click' it.

I've tried

$('ul li a:first').focus();

without luck, but I think I may be misinterpreting the usage of .focus().

Any advice appreciated!

:s

+2  A: 

Yeah, though it's a little odd how it works (and I found this on the jQuery focus docs, and don't claim to understand why it works):

$(document).ready(
  function() {
    $("a:first").attr("tabindex",'-1').focus();
  }
  );

Demo at: jsbin

David Thomas
This has just really come in handy - it's great for giving focus to things that don't usually aquire focus, such as a div. Thanks David!
Cordial
+3  A: 

Your code is almost right. You just miss $(document).ready.

To fix, use this:

$(document).ready(function(){
   $('ul li a:first').focus();
});

See example in jsfiddle.

The problem is when jquery is called the page doesn't have that link yet. With $(document).ready. you call jquery only when page is complete.

Topera