stack stack - 5 months ago 7
jQuery Question

How do I determine switching textarea focused?

I have two testarea:

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


Now I want to show this message
textarea 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 none of those textarea(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?

Answer

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>