stack
stack

Reputation: 10228

How do I determine switching textarea focused?

I have two textarea:

<textarea id="one"></textarea>
<textarea id="two"></textarea>

Now I want to show this message text area was focused once until focus on the another textarea.

Something like this:

var el;
$("body").on('focus', 'textarea', function(e) {

  if (el != $(this)) {
    alert('new textarea is focused now');
  }
  
  el = $(this);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea id="one"></textarea>
<textarea id="two"></textarea>

This ^ code works if I never blur any of those text area(s) after first focused. But if I blur one of them, then this variable el will be empty .. How can I keep $(this) into el forever?

Upvotes: 0

Views: 85

Answers (2)

Shafizadeh
Shafizadeh

Reputation: 10340

All you need is using this instead of $(this), like this:

var el;
$("body").on('focus', 'textarea', function(e) {

  if (el != this) {
    alert('new textarea is focused now');
  }
  
  el = this;

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<textarea id="one"></textarea>
<textarea id="two"></textarea>

Upvotes: 1

Tcorb
Tcorb

Reputation: 11

You have an alert which will blur the rest of the page. Once you dismiss the alert dialog the text area wil be back into focus. This creates a crazy and never ending cycle of (event - alert - event). use return to exit once it fires.

Upvotes: 1

Related Questions