jquery onを使ってイベントをbind(バインド)する

jquery onを使ってイベントをbind(バインド)する

jqueryで focusoutメソッドを利用してテキストフォームからフォーカスが外れたイベントを取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • jquery 3.5.1

※windows10にApacheのインストールはこちら

focusoutメソッド利用

テキストフォームから、フォーカスが外れた際にテキストが表示されてます。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous">
  <script src="http://code.jquery.com/jquery-3.5.1.min.js"></script>  
</head>
<style>
.container {
  margin: 0 auto;
  margin-top: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 30px;
}
</style>
<script>
$(function(){
  //フォーカスが外れたことを確認
  $('#formGroupExampleInput').focusout(function(){
    $('#piyo').text("テキストフォームからフォーカスが外れました");
  });
  //フォーカスがあたったを確認
  $('#formGroupExampleInput').focusin(function(){
    $('#piyo').text("テキストフォームにフォーカスがあたりました");
  });
});
</script>
<body>
  <div class="container">
    <div id="piyo"></div>
    <form>
      <div class="form-group">
        <label for="formGroupExampleInput">text</label>
        <input type="text" class="form-control" id="formGroupExampleInput" placeholder="">
      </div>      
    </form>  
  </div>
</body>
</html>

フォーカス外れるとテキストが表示されることが確認できます。