jquery focusメソッドを使ってフォーカスを指定した要素に移動させる

jquery focusメソッドを使ってフォーカスを指定した要素に移動させる

jqueryでhoverメソッドを使ってマウスが要素にカーソルが当たったときと離れたときのイベントを取得するサンプルコードとなります。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43

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

focus利用

ボタンをクリックして、フォーム「email」にフォーカスをあてます。

<!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(){
  $('.btn').click(function(){
    $('#exampleInputEmail1').focus();
  });
});
</script>
<body>
  <div class="container">    
    <form>
      <div class="form-group">
        <label for="exampleInputEmail1">Email address</label>
        <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
        <small id="emailHelp" class="form-text text-muted"></small>
      </div>
      <div class="form-group">
        <label for="exampleInputPassword1">Password</label>
        <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
      </div>      
      <button type="submit" class="btn btn-primary">フォーカスを移動</button>
    </form>
  </div>
</body>
</html>

実行結果を確認すると、ボタンをクリックしたタイミングでフォーカスが移動することが確認できます。