views:

44

answers:

2

I have a text field that I would like to maintain focus, no matter what.

The problem is, my page loads an iframe (cross domain), the contents of which steal the focus. What's more, the user might be typing in my text field as the iframe steals focus, causing the user to type in the iframe's text field instead.

I've tried spamming the .focus() event, in the hopes that if it gets blurred, it will refocus near instantly. It seems like this would work, but what happens is it doesn't switch focus back fast enough -- the user is still able to type in the iframe's focused field.

Is there a way to prevent blur from occurring at all? Or a faster way to switch focus back to my text field?

Here's what I've tried, which doesn't work completely:

//get the textbox DOM element to focus.
var my_textbox = $("#my_textbox").get(0);
//pretty straight-forward -- focus it.
var setFocus = function(){
  my_textbox.focus();
}

//every 10ms refocus our textbox.
//apparently, 10ms is not fast enough, as some typing
//still occurs in the iframe's textfield.
setInterval(setFocus, 10);

Note: I did just as a similar question yesterday, but I think this one gets to the root of the problem. I hope it's ok.

Thanks for your help, any ideas are appreciated.

+2  A: 

Have you tried this?

//get the textbox DOM element to focus.
var my_textbox = $("#my_textbox").get(0);

my_textbox.onblur = function(){
  my_textbox.focus();
};

Still feels pretty kludgey, but I think this is what you're going for.

Eric Mickelsen
+1  A: 

This just sounds like a bad idea. If your field and the iframe's field are both fighting over focus you could cause an infinite-loop and hang their browser, or you may just make it impossible to type into either field. And what if the user wants to type into the iframe's field? If I went to a site that behaved like you describe, I'd leave and never return.

If there's something that requires the users immediate, undivided attention like you're implying then it should be the only thing on the page, similar to many login pages.

bemace
Agreed - I have never experienced hanging or being unable to focus on a different field before but thats not to say it doesnt exist. I too would turn away from a site never to return if it does either of these. Its best to have little content on the page if you require the user to pay attention to a field. Try also enlarging the textbox and maybe giving it a red border or an alert image next to it or something.
ClarkeyBoy