LoginSignup
13
22

More than 5 years have passed since last update.

スマホで閲覧時のみ、電話番号にtel:リンクを追加する

Posted at

やりたいこと

  • スマホで見たときに、タップするだけで電話がかけられるように電話番号にリンクをはりたい。
  • でもPCで見たときはリンクさせたくない。
  • それを同じHTMLで済ませたい。
  • テキストだけでなく、画像でも同様にしたい。

ということで、JavaScript(jQuery)を使います。
デモ

jQueryで電話番号リンクを追加する

HTML
<!-- テキストの場合 -->
<p class="tel">00-1234-5678</p>

<!-- 画像の場合は、alt属性に電話番号を入れておきます。 -->
<p class="tel">
<img src="https://placehold.jp/150x150.png" alt="01-1234-5678">
</p>
JS
$(function() {
  $('.tel').each(function() {
//.tel内のHTMLを取得
    var str = $(this).html();
//子要素がimgだった場合、alt属性を取得して電話番号リンクを追加
    if ($(this).children().is('img')) {
      $(this).html($('<a>').attr('href', 'tel:' + $(this).children().attr('alt').replace(/-/g, '')).append(str + '</a>'));
    } else {
//それ以外はテキストを取得して電話番号リンクを追加
      $(this).html($('<a>').attr('href', 'tel:' + $(this).text().replace(/-/g, '')).append(str + '</a>'));
    }
  });
});

そうすると、動的にtelリンクが追加され、HTMLは以下のようになります。

HTML
<!-- テキストの場合 -->
<p class="tel">
<a href="tel:0012345678">00-1234-5678</a>
</p>

<!-- 画像の場合 -->
<p class="tel">
<a href="tel:0112345678">
<img src="https://placehold.jp/150x150.png" alt="01-1234-5678">
</a>
</p>

スマホのみ適用させる

上記コードをスマホ閲覧時のみ適用させるようにします。
以前書いた記事をそのまま使用。
スマホで閲覧した時だけJavaScriptを一部無効化したり有効化したりする

JS
if(navigator.userAgent.match(/(iPhone|iPad|iPod|Android)/)){

}

まとめ

HTML
<p class="tel">00-1234-5678</p>

<p class="tel">
<img src="https://placehold.jp/150x150.png" alt="01-1234-5678">
</p>
JS
if (navigator.userAgent.match(/(iPhone|iPad|iPod|Android)/)) {
  $(function() {
    $('.tel').each(function() {
      var str = $(this).html();
      if ($(this).children().is('img')) {
        $(this).html($('<a>').attr('href', 'tel:' + $(this).children().attr('alt').replace(/-/g, '')).append(str + '</a>'));
      } else {
        $(this).html($('<a>').attr('href', 'tel:' + $(this).text().replace(/-/g, '')).append(str + '</a>'));
      }
    });
  });
}
13
22
2

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
13
22