FacebookのPage Pluginをレスポンシブ対応させるjQueryの書き方

Page Pluginがはみ出る!

FacebookのLike BoxがPage Pluginに変わって、しばらくしてからふと気付いてしまったんです。

「あれ?親要素の幅が変わってるのに、Page Pluginの横幅が伸縮してへんぞ?」と。

Page Pluginはレスポンシブデザインには非対応

実はFacebook DevelopersのPage Pluginのページにバッチリ書いてありました。

No Dynamic Resizing

The Page plugin works with responsive, fluid and static layouts. You can use media queries or other methods to set the width of the parent element, yet:

  • The plugin will determine its width on page load
  • It will not react changes to the box model after page load.

If you want to adjust the plugin's width on window resize, you manually need to rerender the plugin.

要約すると「ウィンドウとか親要素のリサイズにあわせてダイナミックにPage Pluginの横幅を変更したかったら、自分で再描画の処理つくってね」ということ。

だからPage Pluginを再描画する処理をjQueryで作った

パーフェクトなレスポンシブ対応が実装できるわけではありません。
やっぱりwidthの最大幅は500pxであることに変わりはありませんし。

ですが、180px〜500pxの間であればwindowのresizeに対応するので、bootstrap3などでレスポンシブを実装している場合には役に立つとおもいます。

$(function() {
    var fbUrl = 'あなたのFacebookページのURL',
        fbTitle = 'あなたのFacebookページのタイトル';

    $(window).resize(function () {
        $('#fbPagePlugin').html('<div class="fb-page" data-href="' + fbUrl + '" data-width="500" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true" data-show-posts="true"><div class="fb-xfbml-parse-ignore"><blockquote cite="' + fbUrl + '"><a href="' + fbUrl + '">' + fbTitle + '</a></blockquote></div></div>');
        window.FB.XFBML.parse();
    });
});

上記のソースの中で「あなたの~」となっている変数、fbUrlとfbTitleの内容を適宜書き換えてください。

レスポンシブデザインのサイトに組み込むことを前提にしているので、data-widthは500、data-adapt-container-widthはtrueにしてあります。