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

jqueryでhoverメソッドを使ってマウスが要素にカーソルが当たったときと離れたときのイベントを取得するサンプルコードとなります。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
※windows10にApacheのインストールはこちら
focus利用
ボタンをクリックして、フォーム「email」にフォーカスをあてます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<!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> |
実行結果を確認すると、ボタンをクリックしたタイミングでフォーカスが移動することが確認できます。

-
前の記事
Rails6 cssフレームワーク「Cardinal」を使用する手順 2020.08.04
-
次の記事
php ライブラリ「PHPMailer」を使ってメールを送信する 2020.08.04
コメントを書く