Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force focus on one element with an exception. (jQuery)

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?

like image 324
Luke Burns Avatar asked Jul 12 '10 14:07

Luke Burns


2 Answers

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

like image 198
Gabriele Petrioli Avatar answered Sep 28 '22 04:09

Gabriele Petrioli


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();
}
like image 37
Weston C Avatar answered Sep 28 '22 04:09

Weston C