0

I am trying to REAL prevent a DOM element from losing focus. I've read some solutions from here e.g.:

StackOverflow solution 1

StackOverflow solution 2

StackOverflow solution 3

But there are only sneaky solutions that (RE)set focus on an element again and again. But when testing this solutions in fiddle i just write simnple:

$('input').on('focusout', function() { console.log('focus lost'); });

It shows me that element is losing focus.

So my question is: is possible to REAL prevent an element from losing focus? something like this?:

$('input').on('focusout', function(e) { e.preventDefault() }); <--this not working but i want to get this result in any other way

Community
  • 1
  • 1
Sheryf
  • 71
  • 2
  • 13

1 Answers1

0

There isn't a REAL way for preventing an element from losing focus. It is because than when you click outside browser window, the element will always lose focus.

The trick you listed are some ways to solve this problem.

Piotr Stapp
  • 19,392
  • 11
  • 68
  • 116
  • So this is out of my control :(. I want to get result like this: I have 1 text input, and it should normally lose focus when tabbing or clicking elsewhere but... I want to have an element ( e.g button) that is clicked dont remove focus from this element. Its all because i want to bind blure event on this input element, but this event shouldnt trigger when button is clicked. – Sheryf Aug 11 '14 at 09:46
  • @Sheryf I'm pretty sure you can easily get around it. For example you could use some flag to check whether the button is clicked, or try checking which element triggered the blur using something like [this](http://stackoverflow.com/a/11544766/2333214) – T J Aug 11 '14 at 10:39
  • @Tilwin Joy. I work hard on this solution. My brain is in fire. I can't do anything in click eventHandler because when button is clicked, input lose focus immediately and blur event of that input trigger up (It goes random, sometimes click trigger before blur). I set delegate for this events(their parent element), when i checked the order of evenst is set in delegate it shows `Object{ click=[1], focusout=[1]}` but still it goes random. – Sheryf Aug 11 '14 at 11:27
  • sorry about commenting below another answer, @Sheryf What i'm saying is that, you can add the code to be executed on `blur` in a silly `timeOut` like 20ms. You can set a variable to `true` on buttons click. Inside the blur function, you need to check for this variable and continue execution accordingly. If it is true, you avoid executing the code and reset the variable. – T J Aug 11 '14 at 11:36
  • [Fiddle](http://jsfiddle.net/89ks6mjm/5/) <- here u got example. Please check events I add between comment (/****CHECk HERE****/). Now im trying ur solution from comment. Well be back in a few minutes. – Sheryf Aug 11 '14 at 11:52
  • @Tilwin Joy. I used flag and delay on blur event (100ms). It works but I am still not satisfied with this solution ;/. Anyways Thanks. – Sheryf Aug 11 '14 at 12:12