LoginSignup
1
2

More than 3 years have passed since last update.

入力フォームの文字をtwitterに共有する方法

Last updated at Posted at 2020-08-14

完成版

スクリーンショット 2020-08-14 20.34.03.png
入力してボタンを押すと、
スクリーンショット 2020-08-14 20.36.04.png
このようにご自身のTwitterアカウントに文字が入力されている状態です。

作成

使用環境: HTML5

index.html
<!--入力フォーム-->
<input type="text" id="content">
<!--ご自身のTwitterアカウントへ行きます-->
<button id="twitter" class="btn" type="button">Tweet</button>

<script>
  // twitter共有機能
        document.getElementById("twitter").addEventListener('click', function(event) {
        event.preventDefault();
        var left = Math.round(window.screen.width / 2 - 275);
        var top = (window.screen.height > 420) ? Math.round(window.screen.height / 2 - 210) : 0;
        window.open(
            "https://twitter.com/intent/tweet?text=" + encodeURIComponent(document.getElementById("content").value),
            null,
            "scrollbars=yes,resizable=yes,toolbar=no,location=yes,width=550,height=420,left=" + left + ",top=" + top);
    });
</script>    

これで共有機能が完成しました。

bootstrapやCSSを導入するとtwitterのボタンらしくなります
使用環境: HTML5 Bootstrap4

index.html
<!--buttonスタイルを整える-->
<button id="twitter" class="btn" style="background-color:#00aced; color:white;" type="button"><i class="fab fa-twitter"></i> Tweet</button>

<input type="text" id="content">
<script>
  // twitter共有機能
        document.getElementById("twitter").addEventListener('click', function(event) {
        event.preventDefault();
        var left = Math.round(window.screen.width / 2 - 275);
        var top = (window.screen.height > 420) ? Math.round(window.screen.height / 2 - 210) : 0;
        window.open(
            "https://twitter.com/intent/tweet?text=" + encodeURIComponent(document.getElementById("content").value),
            null,
            "scrollbars=yes,resizable=yes,toolbar=no,location=yes,width=550,height=420,left=" + left + ",top=" + top);
    });

</script>

<!--bootstrap導入-->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script defer src="https://use.fontawesome.com/releases/v5.7.2/js/all.js"></script>

スクリーンショット 2020-08-14 21.02.02.png

先程よりtwitterのボタンらしくなりました。

参考

text_areaの内容をtwitterにシェアする https://teratail.com/questions/172448

1
2
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
1
2