WordPressテーマ作成~jQueryを追加する~
投稿日
更新日
テーマ作成をする時に、jQueryを記述する時のやり方です。
今回は、TOPに戻るボタンの実装です。
まずは、JS用のフォルダとファイルを作成していきます。
階層は、こんな感じ。
\wp-content\themes\aman13.com\js\script.js
テーマ用フォルダの中にJSフォルダを作って、その中にJSファイルを作る。
fanctions.phpにjQueryを使えるようにする記述をしていきます。
前に、下記を記述しているので、その中に、記述します。
1 2 3 |
function theme_scripts() { } |
下記コードを追加します。
パスはフォルダとかファイル名とかは今回作成したものに合わせてください。
1 |
wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/script.js', array( 'jquery' ), $version, true ); |
HTMLとCSSで表示させるボタンを書いていきます。どのページでも出るようにfooter.phpに書くのがおすすめ。
(これは自分が見せたい内容にしてOK)
1 2 3 |
<div id="move-to-the-top" class="move-to-the-top"> <span class="dashicons dashicons-arrow-up-alt2"></span> </div> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
.move-to-the-top { background: #444444; border-radius: 25px; bottom: 20px; color: #ffffff; cursor: pointer; height: 50px; position: fixed; right: 20px; width: 50px; z-index: 9999; } .move-to-the-top span { align-items: center; display: flex; height: 50px; justify-content: center; width: 50px; } |
こんな感じで、表示されるようにしたら、JSファイルにjQueryを記述します。
TOPに戻るまでの動く時間はお好みで変えてください。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
;(function($) { "use strict"; $(function() { var event = "ontouchend" in window ? "touchend" : "click", elmMove = $("#move-to-the-top"); elmMove.on(event, function(e) { e.preventDefault(); $('html, body').animate({scrollTop: 0}, 500); }); }); })(jQuery); |
これで完成!!