フォームのオートフォーカスを有効にしてユーザーエクスペリエンスを向上させたいとお考えですか?オートフォーカスを使用すると、ページの読み込みが終了したときに最初のフォームフィールド内でカーソルが自動的にアクティブになり、ユーザーとのインタラクションが効率化されます。このシンプルな機能拡張は JavaScript のコードスニペットで実現できます。
フォームの作成
まず、フォームを作成し、フォームフィールドを追加します。フォームの作成にヘルプが必要な場合は、こちらのドキュメントをご覧ください。
オートフォーカスを追加するスニペットの作成
次に、このコード・スニペットをあなたのサイトに追加する必要がある。
スニペットをサイトに追加する際にヘルプが必要な場合は、こちらのチュートリアルをご覧ください。
/** * Add autofocus to the first form field of the form * * @link https://wpforms.com/developers/how-to-add-autofocus-on-your-form/ */ function wpf_dev_autofocus() { ?> <script type="text/javascript"> jQuery(document).ready(function() { var first_input = jQuery( 'form.wpforms-form input[type=text]:visible:enabled:first, textarea:visible:enabled:first' )[0]; if (first_input != undefined) { first_input.focus(); } }); </script> <?php } add_action( 'wpforms_wp_footer_end', 'wpf_dev_autofocus', 10 );
このコード・スニペットはWPFormsにのみ適用されます。forms.wpforms-formを探し、フォームの最初のフォーム・フィールドを探し、このフィールドに:focus要素を即座に追加するからです。
これで完了です! これで WPForms を使ったすべてのフォームにオートフォーカス機能が実装できました。もっとフォーカスを目立たせる CSS を追加したいですか? フォームフィールドのフォーカスに CSS を追加する方法」の記事をご覧ください。
参考アクション
よくあるご質問
Q: 複数ページのフォームでオートフォーカスを有効にしておくにはどうすればよいですか?
A:複数ページのフォームがある場合は、次のコードスニペットを使用してください。
/** * Add autofocus to first form field of form * * @link https://wpforms.com/developers/how-to-add-autofocus-on-your-form/ */ function wpf_dev_autofocus() { ?> <script type="text/javascript"> jQuery(document).ready(function() { var first_input = jQuery( 'form.wpforms-form input[type=text]:visible:enabled:first, textarea:visible:enabled:first' )[0]; if (first_input != undefined) { first_input.focus(); } jQuery( '.wpforms-page-next' ).on("click", function() { var page_first_input = jQuery(this).closest( '.wpforms-page' ).next().find( 'input, textarea' ).first(); if (page_first_input != undefined) { setTimeout(function() { page_first_input.focus(); }, 100); } }); }); </script> <?php } add_action( 'wpforms_wp_footer_end', 'wpf_dev_autofocus', 10 );