上毛印刷株式会社

【JavaScript】SNSアイコンをクリックすると、そのページをディスクリプションを自動で取得して投稿する

【JavaScript】SNSアイコンをクリックすると、そのページをディスクリプションを自動で取得して投稿する

2026年06月29日
WEBサイト制作
  • #HTML
  • #css
  • #JavaScript
  • #tips

こんにちは!
上毛印刷WEB制作担当のソーヤです。

みなさん、SNSは普段使っていますでしょうか。
今の時代、SNSがほぼすべての情報メディアを牛耳っていると言っても過言ではないですよね。
そんなSNSに簡単に貴方が作ったWebサイトを紹介できたら、
便利ですよね?

そんなtipsを紹介します!

実装例


HTML例

<div class="c-sns">
    <ul>
        <li>
        <a href="#" rel="nofollow" target="_blank" onclick="gtag('event', 'click', {'event_category': 'share','event_label': 'facebook'});"><img src="/cp/wp/wp-content/themes/jomo_wp/img/social_icon_fb.png"></a>
        </li>
        <li>
        <a href="#" rel="nofollow" target="_blank" onclick="gtag('event', 'click', {'event_category': 'share','event_label': 'twitter'});"><img src="/cp/wp/wp-content/themes/jomo_wp/img/social_icon_tw.png"></a>
        </li>
        <li>
        <a href="#" rel="nofollow" target="_blank" onclick="gtag('event', 'click', {'event_category': 'share','event_label': 'line'});"><img src="/cp/wp/wp-content/themes/jomo_wp/img/social_icon_line.png"></a>
        </li>
    </ul>
</div>

CSS例

.c-sns {
  z-index: 100;
}
.c-sns ul {
  display: flex;
  justify-content: center;
  list-style: none;
}
.c-sns li {
  margin: 0 10px 0 0;
  border: none;
  width: 30px;
}
.c-sns li:last-of-type {
  margin: 0;
}
.c-sns li a img {
  transition: 0.2s ease;
  width: 100%;
}
.c-sns li a:hover img {
  transform: scale(1.2);
}
@media screen and (max-width: 768px) {
  .c-sns {
    z-index: 1000;
    transition: 0.4s ease;
  }
  .c-sns ul {
    display: flex;
  }
} 

JavaScript例

(function () {
    const pageUrl = encodeURIComponent(location.href);
    const descMeta = document.querySelector('meta[name="description"]');
    const desc = encodeURIComponent(descMeta ? descMeta.content : '');
    const sns = document.querySelector('.c-sns');
    if (!sns) return;
    const links = sns.querySelectorAll('a');
    const urls = [
        'https://www.facebook.com/share.php?u=' + pageUrl,
        'https://twitter.com/intent/tweet?url=' + pageUrl + '&text=' + desc,
        'https://social-plugins.line.me/lineit/share?url=' + pageUrl + '&text=' + desc,
    ];
    links.forEach(function (a, i) {
        if (urls[i]) a.href = urls[i];
    });
})();

まとめ

今回もjQueryではなく、Vanilla.jsで実装してみました。

コピペしてガンガン使ってください!

WEB制作担当ソーヤ

ソーヤ

上毛印刷WEB制作担当
東証プライム企業の本社WEB受託チームにてフロントエンドエンジニアの経験あり。


この記事に対するご意見・ご感想・ご質問等ありましたら、
ぜひ下記フォームにてお送りください。

    お名前必須
    メールアドレス必須
    お問い合わせ内容必須
    PAGE TOP