jQuery Form How to - Detect when user clicks outside of textarea or button








Question

We would like to know how to detect when user clicks outside of textarea or button.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>
$(document).ready(function() {<!--from  ww  w . ja v  a  2s.c om-->
    var $text = $("textarea.textarea"),
        $btn = $("input.submit");
    $(document).on("click focus", function(e) {
        if (!$text.is(e.target) && !$btn.is(e.target) && $text.val() == "") {
           $btn.hide();
        }
        else {
           $btn.show();
        }
        
    });
});

</script>
</head>
<body>
  <div class="wrapper">
    <textarea class="textarea"></textarea>
    <input type="submit" class="submit" value="submit" />
  </div>
</body>
</html>

The code above is rendered as follows: