开发者

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.

开发者_JS百科

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


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/


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/


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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜