0

I have a page with a textarea #content and an input textbox #name. Once the user has clicked on #content, I want to prevent him from loosing focus of that textarea, unless he is clicking on #name.

I've tried the following:

// Prevent loss of focus for textarea
$("#content").on("blur", function(event) {
    $('#name').mouseover(function() {
       return true;
    });
    event.preventDefault();
    this.focus();
    return false;
});

It works just fine to prevent loss of focus of an element. But my idea of checking if he's hovering #name and returning just doesn't work.

Juicy
  • 11,840
  • 35
  • 123
  • 212
  • `$("#name").mouseover(function(){})` doesn't test whether a hover is occurring at that moment, it binds a mouseover handler that will be executed later _if_ a hover occurs later. – nnnnnn Jun 14 '14 at 02:24

2 Answers2

2

Stole the code from here to get the element that triggered the blur.

var clicky;

$(document).mousedown(function(e) {
    // The latest element clicked
    clicky = $(e.target);
});

$("#content").on("blur", function(event) {
    if (clicky.attr('id') == 'name') {
        return true;
    }
    event.preventDefault();
    this.focus();
    return false;
});

fiddle

Community
  • 1
  • 1
Fabricator
  • 12,722
  • 2
  • 27
  • 40
  • This doesn't work, because clicking isn't the only way to change focus. – nnnnnn Jun 14 '14 at 02:26
  • @nnnnnn, but OP only care about when `#name` is clicked? – Fabricator Jun 14 '14 at 02:28
  • With this code, if you click on the name element _first_ you can then use the tab key to move focus around to any other elements, including to the textarea and then to something other than the name element. – nnnnnn Jun 14 '14 at 05:37
1

Something like this, maybe?

$(document).ready(function(){
   var id;
   $('#content').on('blur',function(){
       $(":input").focus(function(){
          id = this.id;
          if(id != 'username' && id != 'content'){ // sorry, changed your id from name to username. 
              $('#content').focus();   
              }
           });       
      });
  });

Working fiddle: http://jsfiddle.net/ugx3S/

faerin
  • 1,915
  • 17
  • 31