WordPressでjQueryを使うときの注意点

お題

ページ内リンクをクリックした際に一気に飛ぶのではなく、スライドして目標のアンカーの場所に移動する機能が欲しい

問題発生

ヘッダーに直に記述したら動作した下記コードをjs化してfunction.phpに条件合致するときのみこのjsを読み込むコードをヘッダーに追加するように指定したけど


……動かない。。


ソースコードを見てみるとちゃんとjsを読み込むコードは存在してるのに



……動かない。


// jQueryの読み込み
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

// smooth_scroll機能部分
<script>
$(function(){
   // #で始まるアンカーをクリックした場合に処理
   $('a[href^=#]').click(function() {
      // スクロールの速度
      var speed = 400; // ミリ秒
      // アンカーの値取得
      var href= $(this).attr("href");
      // 移動先を取得
      var target = $(href == "#" || href == "" ? 'html' : href);
      // 移動先を数値で取得
      var position = target.offset().top;
      // スムーススクロール
      $('body,html').animate({scrollTop:position}, speed, 'swing');
      return false;
   });
});
</script>

原因特定

いろいろ調べてみると、動かない原因と思われることが…
  1. WordPressではjQueryがすでに準備されているので、別に読み込んでくる必要はない
  2. WordPressで用意されているjQueryは特殊で$が使えない

jQueryの読み込み部分をコメントアウトしても動かなかった原因は2つ目の$が使えないが故のよう。

解決

最終的には下記のコードをそれぞれのところに記述して解決

functions.php


// smooth scroll導入
add_action('wp_enqueue_scripts','smooth_scroll');
function smooth_scroll() {
	if(is_home() || is_front_page() || is_admin()) {
		return;
	} else {
		wp_enqueue_script('smoothscroll', get_bloginfo('stylesheet_directory') . '/smooth_scroller.js');
	}
}

smooth_scroller.js



// packaged with string 'jQuery' for using jQuery in WordPress
jQuery(function(){
   // if href string is started '#', this function run
   $('a[href^="#"]').click(function() {
      // scroll speed
      var speed = 400; // milli sec
      // get anchor
      var href= $(this).attr("href");
      // get target
      var target = $(href == "#" || href == "" ? 'html' : href);
      // get target with int
      var position = target.offset().top;
      // smooth scroll
      $('body,html').animate({scrollTop:position}, speed, 'swing');
      return false;
   });
});

ポイント

  1. jQueryはWordpressであらかじめ用意されるものを使うので、外部のものは読み込ませない
  2. $が使えないのでjQuery(function()){ });でパッケージ化する({}内では$が利用できる)
The following two tabs change content below.

Web勉強中おじさん

最新記事 by Web勉強中おじさん (全て見る)

0