Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery blur should not fire if div is clicked/focused

Tags:

jquery

input

blur

I have a standard text input that has a blur event. The blur event should fire when anything in the document is clicked (other than the input AND <div id='show-anyways'></div>).

My problem is that I don't know how to add the <div id='show-anyways'></div> to negate the blur event function.

Hopefully I have explained myself well enough, I know it's kinda a weird situation. Please let me know if you need more info.

like image 841
sadmicrowave Avatar asked Jun 23 '12 22:06

sadmicrowave


2 Answers

Use the event target to determine what is clicked. Following will track all clicks on document and not trigger blur() if element is the DIV or the Input.

var $input=$( '#MY-Input-ID');

$(document).click(function(evt){
   var $tgt=$(evt.target);
   if( !$tgt.is( '#show-anyways') && !$tgt.is($input) ){
         $input.blur()
    }
})

It will not trigger on elements that have any preventPropogation set up.

like image 127
charlietfl Avatar answered Oct 11 '22 23:10

charlietfl


UPDATE: had to completely rewrite my solution. The blur event handler is attached to the event that loses focus: if it was similar to mouseout event, we could know which element will get the focus, but there's no such luck. So we have to resort capturing .click events instead - and trigger some function based on it, instead of listening to blur events.

var inputIsBlurred = function() { 
   console.log('Run away!!!');
};
$(document).click(function(e){
  var $target = $(e.target);
  console.log($target);
  if ($target.is('#some_input') // fired by an input - no special effects
      || $target.is('#show-anyways') // fired by 'show-anyways' div
      || $target.parents('#show-anyways').length > 0 // ... or its children
  ) {
      return true; // move along, nothing to do here
  }
  inputIsBlurred();
});​

Here's a fiddle to play with. Sorry for that confusion caused by my original answer. (

like image 22
raina77ow Avatar answered Oct 11 '22 23:10

raina77ow