AnApprentice
AnApprentice

Reputation: 111030

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

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');
});

Upvotes: 30

Views: 79777

Answers (4)

hunter
hunter

Reputation: 63542

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/

Upvotes: 68

DwB
DwB

Reputation: 38320

I'm not 100% sure that this is what you want, but here is a stab at it:

<html>
<head>
<title>Example</title>
<script src="jquery-1.4.3.js" type="text/javascript"></script>
</head>
<body id="body">
<script>
    $("document").ready( function() 
    {   $("#body").click( function()
        { alert("body"); } );
        $("#input").click( function(event)
        { alert("input"); event.stopPropagation(); } );
    } );
</script>
<h2>input below</h2>
<input id="input" type="text"/>
</body>
</html>

Upvotes: 0

Aaron Hathaway
Aaron Hathaway

Reputation: 4315

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.

Upvotes: 3

jAndy
jAndy

Reputation: 236092

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/

Upvotes: 15

Related Questions