Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Detecting when a user clicks OUT of an input type Text Field

Tags:

jquery

I want to detecting when a user clicks OUT of an input type Text Field, not in.

Here's what I have but both events are firing on click inside (focus):

<input id="title" val="hello" />

$("#title").focusout(function() {
    console.log('inside');
}).blur(function() {
    console.log('outside');
});
like image 494
AnApprentice Avatar asked Jan 03 '11 15:01

AnApprentice


3 Answers

You can bind your focus and blur event like so:

<input id="title" val="hello" type="text" />  $("#title").focus(function() {     console.log('in'); }).blur(function() {     console.log('out'); }); 

focusout isn't necessary since it's geared toward event bubbling for child elements: http://api.jquery.com/focusout/

like image 97
hunter Avatar answered Sep 20 '22 01:09

hunter


You could write a little plugin, like

(function($){   $.fn.outside = function(ename, cb){       return this.each(function(){           var $this = $(this),               self = this;            $(document).bind(ename, function tempo(e){               if(e.target !== self && !$.contains(self, e.target)){                   cb.apply(self, [e]);                   if(!self.parentNode) $(document.body).unbind(ename, tempo);               }           });       });   }; }(jQuery)); 

..and use it like:

$('#title').outside('click', function(e) {     console.log('outside'); }); 

Example: http://www.jsfiddle.net/tGnun/

like image 27
jAndy Avatar answered Sep 22 '22 01:09

jAndy


It's looking like focusout() and blur() are both triggering when you click outside of the text. Try using focus() instead. Check it out here.

like image 43
Aaron Hathaway Avatar answered Sep 22 '22 01:09

Aaron Hathaway