LoginSignup
2
3

More than 5 years have passed since last update.

TwitterのTweetボタンのURLを動的に変える

Posted at

SPA(シングルページアプリケーション)なんかだと、hash bang(#!)を使ってページを変えるパターンがある。
そのとき、TwitterのTweetボタンのURLにhash bangを含めたい。
つまり、動的に変えたい。
それが結構たいへんだった。
答えは以下のURLのとおり。

コードの説明

htmlに次のように、テンプレートと空の領域を用意しておく。
テンプレートのclassはtwitter-share-button以外にし、display:none;で非表示にする。

<a href="https://twitter.com/share" class="twitter-share-button-template" data-url="http://dummy.com" data-hashtags="hashtag" style="display:none;">Tweet</a>
<div id="tweet-area"></div>
  1. 前につくったTweetボタンを削除
  2. テンプレートをclone
  3. cloneしたものからdisplay:none;を外して表示
  4. data-urlを新しいURLにする(この例では今のURLにしている)
  5. twitter-share-buttonにする
  6. 空の領域に作ったTweetボタンを配置
  7. scriptを読み込み、Tweetボタンを設定する
function setTweet(){
    // remove any previous clone
    $('#tweet-area').empty()

    // create a clone of the twitter share button template
    var clone = $('.twitter-share-button-template').clone()

    // fix up our clone
    clone.removeAttr('style'); // unhide the clone
    clone.attr('data-url', location.href);
    clone.attr('class', 'twitter-share-button'); 

    // copy cloned button into div that we can clear later
    $('#tweet-area').append(clone);

    // reload twitter scripts to force them to run, converting a to iframe
    $.getScript('http://platform.twitter.com/widgets.js');
}

原理

うーん、よくわからなかった。
上記サイトで。。。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3