views:

33

answers:

3

I have two input fields. I want to force the focus on #area no matter where the user clicks unless it is on #input. I've tried something like this, but since input is part of document, it does not work.

$("#area").focus();
$(document).click(function() { $("#area").focus() };
$("#input").click(function() { $("#input").focus() };

Thoughts?

+1  A: 

change it to

$("#area").focus();
$(document).click(function() { $("#area").focus() };
$("#input").click(function(e) { e.stopPropagation(); $("#input").focus() };

This will stop the event from bubbling up to the document, and will only be caught by the #input

Gaby
+1  A: 

You need to cancel the event bubbling when clicking on the normal inputs, either by returning false in your event handler, or by calling e.stopPropagation().

I'm not sure if the order in which you assign event handlers matters, but you might try to put the #input event first.

Peter Kruithof
+1  A: 

The stopPropogation solution is simpler than what I'm about to suggest, but it's probably worth discussing this other option. In that first function you've got, you might try taking the first argument to the function, which is a jQuery normalized event object:

$(document).click(function(event) { ...

and testing it to see if the target property of the event is your input:

$(document).click(function(event) {
    if(! (event.target == $("#input").get(0)) )
        $("#area").focus();
}
Weston C
+1, the added benefit of this is that you only need just one function to handle both cases.. The added downside is that for IE you need to test against `event.srcElement` which adds complexity ..
Gaby
Beware that `event` is a reserved keyword in IE, and will give an error when you use this as a variable.Also, the check you provided can be written simpler (and shorter) as `if ($(event.target).is('#input'))`
Peter Kruithof