Тег для номера телефона html5

Ссылки tel: нужны, чтобы сделать кликабельным номер телефона на сайте, а через mailto: можно отправить целое письмо, в котором сразу будут заполнены и адрес, и тема, и даже какой-нибудь текст. Иногда это удобно — пользователю не нужно набирать номер телефона вручную, а письмо в службу поддержки можно начать сразу с конкретной темы.

Такие форматы ссылок поддерживаются всеми браузерами, так что вы можете по необходимости использовать их в своих проектах не переживая, что где-то они не сработают.

mailto:

Ссылка формируется из нескольких частей. Сначала в адресе ставится префикс mailto:, после которого указывается адрес почты. Это самый простой вариант.

<a href="mailto:mail@htmlacademy.ru">Напишите нам</a>

Текст письма указывается с помощью параметра body

<a href="mailto:mail@htmlacademy.ru&body=привет">Напишите нам</a>

За тему письма отвечает параметр subject.

<a href="mailto:mail@htmlacademy.ru&body=привет?subject=вопрос">Напишите нам</a>

Можно даже указать кого-то в копии, для этого используются параметры cc и bcc.

<a href="mailto:blog@htmlacademy.ru&cc=mail@htmlacademy.ru?body=Привет, подпишитесь на рассылку">Напишите нам</a>

Что произойдёт, если кликнуть на ссылку с mailto

Откроется почтовая программа, в которой уже будут заполнены все нужные поля. Например, так ссылку выше обработает программа «Почта» в OS X:

Скриншот программы Почта с заполненными полями из ссылки

Если почтовая программа по умолчанию не установлена, появится окно выбора программы.

Обратите внимание, что адреса с нестандартными символами, например, кавычками или дополнительными знаками @, нужно записывать особым образом. Подробнее об этом и других сложных случаях читайте в >RFC 6068

Как стилизовать mailto

Для стилизации ссылки на электронную почту можно воспользоваться CSS-селектором a[href^="mailto:"].

a[href^="mailto:"] {
  font-size: 16px;
  line-height: 32px;
  color: #000000;
}

Стилизованная ссылка mailto

tel:

Ссылка на номер телефона размечается с помощью специального префикса перед номером телефона — tel:.

<a href="tel:+79001111111">+7-900-111-11-11</a>

Хорошим тоном считается указание в href кода страны. При этом в тексте ссылки номер может быть указан в любом удобном формате. Например, добавляем городской номер на сайте фирмы из Санкт-Петербурга:

Хорошо

<a href="tel:+78121111111">(812) 123-45-67</a>

В href указан номер с кодом страны и города, в тексте ссылки есть код города 812, по которому понятно, что речь о Питере.

Чуть хуже

<a href="tel:+78121111111">123-45-67</a>

В этом случае жители всех городов смогут дозвониться до компании, а короткий номер будет понятен и местным. Случай перейдёт в категорию «плохо», если по сайту непонятно, из какого города компания.

Плохо

<a href="tel:1234567">123-45-67</a>

Телефоны с питерскими сим-картами дозвонятся по этому городскому номеру, но жители других городов попадут куда-то ещё.

Другое обязательное требование RFC 3966 — номер телефона, указанный в href, должен быть явно виден на странице.

Хорошо

Звоните <a href="tel:+79001111111">8-900-111-11-11</a> по любому поводу. 

Номер видно в тексте ссылки.

Плохо

<a href="tel:+79001111111">Звоните</a> по любому поводу.

Номер не видно в тексте ссылки, непредсказуемое поведение.

Что произойдёт, если кликнуть на ссылку с tel

На смартфоне откроется приложение-звонилка, в котором будет набран указанный в ссылке номер. Если открыть такую ссылку на компьютере, где есть программа для звонков, произойдёт то же самое. Но вообще то, что произойдет, сильно зависит от устройства и операционной системы, браузера и устройства.

  • Android, iOS — откроется звонилка по умолчанию.
  • Chrome, Edge, Firefox на Windows — откроется предложение использовать какую-нибудь программу для звонка.
  • Safari — если номера нет в списке контактов, то появится подтверждение вызова, после этого откроется FaceTime.

Например, Chrome на OS X предложить открыть FaceTime для звонка, так как эта программа установлена по умолчанию. Вместо неё легко может быть Skype или любая другая звонилка.

Google Chrome предлагает открыть facetime для звонка после клика по ссылке

Windows на ноутбуке предложит выбрать, с помощью какой программы открывать ссылки tel:

Диалоговое окно выбора программы для звонков по умолчанию в Windows

Как стилизовать

С помощью CSS-селектора a[href^="tel:"].

a[href^="tel:"] {
  font-size: 16px;
  line-height: 32px;
  text-decoration: none;
  color: #000000;
}

А так можно добавить иконку телефона из Unicode, которая есть во всех системах:

a[href^="tel:"]:before {
  content: "260e";
  margin-right: 0.5em;
}

Получится такой результат:

Стилизованная ссылка tel с иконкой телефона

Дополнительные материалы по теме

  • RFC 6068 — The ’mailto’ URI Scheme
  • RFC 3966 — The tel URI for Telephone Numbers
  • The Current State of Telephone Links

Ещё о вёрстке

  • Как убрать подчёркивание ссылок
  • Как сделать список без точек в HTML
  • В чём отличие aside и article

I want to mark up a phone number as callable link in an HTML document. I have read the microformats approach, and I know, that the tel: scheme would be standard, but is quite literally nowhere implemented.

Skype defines, as far as I know, skype: and callto:, the latter having gained some popularity. I assume, that other companies have either other schemes or jump on the callto: train.

What would be a best practice to mark-up a phone number, so that as many people as possible with VoIP software can just click on a link to get a call?

Bonus question: Does anyone know about complications with emergency numbers such as 911 in US or 110 in Germany?

Update: Microsoft NetMeeting takes callto: schemes under WinXP. This question suggests, that Microsoft Office Communicator will handle tel: schemes but not callto: ones. Great, Redmond!

Update 2: Two and a half years later now. It seems to boil down to what you want to do with the number. In mobile context, tel: is the way to go. Targeting desktops it’s up to you, if you think your users are more Skype people (callto:) or will more likely have something like Google Voice (tel:) installed. My personal opinion is, when in doubt use tel: (in line with @Sidnicious’ answer).

Update 3: User @rybo111 noted, that Skype in Chrome has meanwhile jumped on the tel: bandwagon. I cannot verify this, because no machine with both at hand, but if it’s true, it means we have finally a winner here: tel:

Displaying a phone number on your website can help increase trust in your business, attract prospective customers, and delight existing ones.

Website visitor contacting business through HTML telephone link

To make it as easy as possible for users to get in touch with you or someone on your team, you can make the phone number clickable in HTML. This is a great UX strategy considering that mobile accounts for approximately half of web traffic worldwide. Meaning, over half of your website visitors will be using the same device to find your business online and to place the call.

In this post, we’ll walk through the process of creating HTML telephone links, or “click to call” links.

Download Now: 25 HTML & CSS Hacks [Free Guide]

How to Link a Telephone Number in HTML

  1. Create an anchor element.
  2. Enter your phone number in the href attribute.
  3. Add tel: before the number inside the quotation marks.
  4. Include text in the anchor element.

1. Create an anchor element.

To start, create an anchor element with an empty href attribute. It will look like this:

 
<a href=""></a>

2. Enter your phone number in the href attribute.

Place the phone number inside the href attribute inside the opening a tag. This href (hypertext reference) attribute ensures the hyperlink is functional. It will look like this:

 
<a href="6031112298"></a>

3. Add tel: before the number inside the quotation marks.

Now add tel: inside the href attribute, before the phone number. Both the tel: and phone number should be inside the quotation marks with no spaces or dashes. It will look like this:

 
<a href="tel:6031112298"></a>

4. Include text in the anchor element.

You can include text in the anchor element. Although it’s not required, it can make the call-to-action more obvious to users. Here’s the code side by side with how it would appear to users on the front end of a website.

See the Pen How to Link a Telephone Number in HTML [With Linked Text] by HubSpot (@hubspot) on CodePen.

If you’d like to include the telephone number and have it be the only text that’s linked, then wrap the phone number in the anchor element and place it inside a paragraph tag. It will look like this:

See the Pen How to Link a Telephone Number in HTML [With Text] by HubSpot (@hubspot) on CodePen.

How to Link a Telephone Number With an Extension in HTML

If the telephone number you’d like to make clickable has an extension, then you’ll need to take an additional step.

  • You create an anchor element.
  • Enter tel: and the phone number in the href attribute.
  • Now, after the phone number, add the letter “p” and the extension number. It will look like this:
 
<a href="tel:6031112298p000"></a>

When clicking this “click to call” link, the user will hear the number dialed, then a one-second pause, then the extension dialed.

How to Link a Telephone Number With a Country Code in HTML

If the telephone number you’d like to make clickable has a country code, then you’ll need to take a different additional step.

  • You create an anchor element.
  • Enter tel: and the phone number in the href attribute.
  • Now, before the phone number, add the plus icon (+) and the country code. It will look like this:
 
<a href="tel:+16031112298p000"></a>

How to Add a HTML Telephone Link to Your Website

An HTML telephone link, or “click to call” link, can be included in various parts of your website. Your contact page and header or footer are among the most common. Let’s look at examples of including these clickable links on a WordPress website.

Contact Page

The exact steps to add a HTML telephone link to a contact page will vary depending on what platform and template you use. Below is the general process.

  • To start, select a predesigned contact page template.
  • Then click into the block with the example phone number.
  • Click the three dots icon.
  • Click Edit as HTML.

How to Add a HTML Telephone Link to Your Contact Page in WordPress: Edit as HTML

  • Replace the existing phone number with the anchor element: <a href=»tel:6031112298″>(603)111-2298</a>

How to Add a HTML Telephone Link to Your Contact Page in WordPress: Add anchor element

  • Click Save Draft and Preview.

How to Add a HTML Telephone Link to Your Contact Page in WordPress: Preview click to call link

Header and Footer

The exact steps to add a HTML telephone link to a header or footer will vary depending on what platform and template you use. Below is the general process.

  • In your dashboard, click Appearance > Widgets.

How to Add a HTML Telephone Link to Your Footer in WordPress: Click widgets

  • In the section labelled “Footer,” add any blocks that you want. For the sake of this demo, I’ll only add a paragraph block.

How to Add a HTML Telephone Link to Your Footer in WordPress: Add blocks to footer widget

  • When you’re ready, click Update.
  • Now go to one of your pages.
  • Scroll down to the footer area and click the paragraph block.

How to Add a HTML Telephone Link to Your Footer in WordPress: Edit paragraph block

  • Add your phone number, then click the three dots icon.
  • Click Edit as HTML.

How to Add a HTML Telephone Link to Your footer in WordPress: Click edit as HTML

  • Wrap the phone number in an anchor element and add href=»tel:6031112298″ to the opening tag.

How to Add a HTML Telephone Link to Your Footer in WordPress: Add anchor element

  • Click Save Draft and Preview.

How to Add a HTML Telephone Link to Your Footer in WordPress: Preview call to click link

How to style a HTML Telephone Link

To style a HTML telephone link, you’ll have to add some custom CSS.

For example, say you want the telephone number to appear bolded, orange, and with no underline. Here’s the CSS and how the “click to call” link would appear on the front end:

See the Pen How to style a HTML Telephone Link by HubSpot (@hubspot) on CodePen.

How you add this CSS to your website depends on the platform you’re using.  If building your site in WordPress, for example, you’d add this CSS to the Additional CSS tab in the WordPress Customizer.

How to style a HTML Telephone Link in WordPress Customizer

Adding “Click to Call” Links to Your Website

Displaying a phone number on your website can help attract and delight prospective and existing customers — making them clickable is even better for UX. The good news is that creating telephone links is easy. You just need to know some HTML and CSS to create and style these links and embed them in different areas on your site.

coding templates

Ставим правильные ссылки на телефонные номера

Многие бизнес-сайты показывают телефонные номера, чтобы их клиенты могли связаться с ними. В эпоху популярности настольных компьютеров пользователи записывали телефонный номер на бумажку и звонили с отдельного устройства.

Сейчас же, пользователи сёрфят в интернете и звонят с одного и того же устройства. Это открывает возможность добавить ссылку на звонок — создать HTML-номер телефона, по которому можно кликать.

Как работают кликабельные ссылки

Сделать номер телефона кликабельным легко с помощью HTML5, который включает в себя специализированный протокол tel:.

Браузеры по-разному интерпретируют этот протокол. Некоторые открывают номернабиратель вашего телефона и добавляют номер на дисплей, ожидая, пока вы нажмете кнопку вызова. Другие сразу делают звонок, а третьи спрашивают что делать.

При клике по такой ссылке на десктопе с установленным приложением Skype (или аналогичным) браузер запросит у вас подтверждение на открытие внешней программы.

Добавление на сайт

Вставьте следующий код в нужное место вашего сайта для показа кликабельной ссылки на телефон:

<a href="tel:123-456-7890">123-456-7890</a>

Если вместо телефона вы хотите видеть ссылку с текстом «Позвонить», то код будет таким:

<a href="tel:123-456-7890">Позвонить</a>

При щелчке на такую ссылку откроется номернабиратель вашего устройства (планшет, телефон).

Добавочный номер

Многие телефоны имеют добавочные номера, чтобы их указать, необходимо использовать разделитель P, который добавит секундную задержку между набором основного и добавочного номеров:

<a href="tel:123-456-7890p123">Позвонить</a>

Если добавочный номер нужно вводить в тональном режиме, используйте разделитель w вместо p.

Код страны

Коды стран могут быть добавлены в телефонный номер при помощи символа + перед самим номером. Например, для России (+7) это будет выглядеть так:

<a href="tel:+7-456-7890">123-456-7890</a>

Микроразметка под SEO

Одна из самых приятных плюшек, когда при поиске местных компаний Google в результатах поиска выдает номер телефона, по которому можно кликнуть.

Решается этот вопрос при помощи микроданных и микроформатов. Добавив пару дополнительных тегов в разметку вашего сайта, вы получите кликабельный номер в SERP. Пользователи будут несказанно рады:

<div itemscope itemtype="https://schema.org/LocalBusiness">
    <h1 itemprop="name">Рога и Копыта</h1>
    Телефон: <span itemprop="telephone"><a href="tel:+7123456890">+7 (234) 567-890</a></span>
</div>

Ссылки

  • Telephone Links: How to Add “Call-able” Links & CTA’s to Your Website

phones tips tricks

<input> элемент типа tel используется чтобы разрешить пользователю вводить и редактировать номер телефона. В отличии от<input type="email"> и <input type="url"> , введённое значение не проверяется автоматически по определённом формату, перед тем как форма может быть отправлена , потому что форматы телефонных номеров сильно различаются по всему миру

Интерактивный пример

Despite the fact that inputs of type tel are functionally identical to standard text inputs, they do serve useful purposes; the most quickly apparent of these is that mobile browsers — especially on mobile phones — may opt to present a custom keypad optimized for entering phone numbers. Using a specific input type for telephone numbers also makes adding custom validation and handling of phone numbers more convenient.

Примечание: Browsers that don’t support type tel fall back to being a standard text (en-US) input.

Value A DOMString representing a telephone number, or empty
Events change (en-US) and input (en-US)
Supported Common Attributes autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, and size
IDL attributes list, selectionStart, selectionEnd, selectionDirection, and value
Methods select() (en-US), setRangeText() (en-US), setSelectionRange()

Value

The <input> element’s value attribute contains a DOMString that either represents a telephone number or is an empty string ("").

Additional attributes

In addition to the attributes that operate on all <input> elements regardless of their type, telephone number inputs support the following attributes:

Attribute Description
maxlength The maximum length, in UTF-16 characters, to accept as a valid input
minlength The minimum length that is considered valid for the field’s contents
pattern A regular expression the entered value must match to pass constraint validation
placeholder An example value to display inside the field when it has no value
readonly A Boolean attribute which, if present, indicates that the field’s contents should not be user-editable
size The number of characters wide the input field should be onscreen

maxlength

The maximum number of characters (as UTF-16 code units) the user can enter into the telephone number field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the telephone number field has no maximum length. This value must also be greater than or equal to the value of minlength.

The input will fail constraint validation (en-US) if the length of the text entered into the field is greater than maxlength UTF-16 code units long.

minlength

The minimum number of characters (as UTF-16 code units) the user can enter into the telephone number field. This must be an non-negative integer value smaller than or equal to the value specified by maxlength. If no minlength is specified, or an invalid value is specified, the telephone number input has no minimum length.

The telephone number field will fail constraint validation (en-US) if the length of the text entered into the field is fewer than minlength UTF-16 code units long.

pattern

{{page(«/en-US/docs/Web/HTML/Element/input/text», «pattern-include»)}}

See Pattern validation below for details and an example.

placeholder

The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds.

If the control’s content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.

Note: Avoid using the placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See <input> accessibility concerns for more information.

readonly

A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by JavaScript code directly setting the HTMLInputElement value property.

Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.

size

The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font (font settings in use).

This does not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength attribute.

Non-standard attributes

The following non-standard attributes are available to telephone number input fields. As a general rule, you should avoid using them unless it can’t be helped.

Attribute Description
autocorrect Whether or not to allow autocorrect while editing this input field. Safari only.
mozactionhint A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for Android only.

autocorrect
Non-standard

{{page(«/en-US/docs/Web/HTML/Element/input/text», «autocorrect-include»)}}

mozactionhint
Non-standard

{{page(«/en-US/docs/Web/HTML/Element/input/text», «mozactionhint-include»)}}

Using tel inputs

Telephone numbers are a very commonly collected type of data on the web. When creating any kind of registration or e-commerce site, for example, you will likely need to ask the user for a telephone number, whether for business purposes or for emergency contact purposes. Given how commonly-entered phone numbers are, it’s unfortunate that a «one size fits all» solution for validating phone numbers is not practical.

Fortunately, you can consider the requirements of your own site and implement an appropriate level of validation yourself. See Validation, below, for details.

Custom keyboards

One of the main advantages of <input type="tel"> is that it causes mobile browsers to display a special keyboard for entering phone numbers. For example, here’s what the keypads look like on a couple of devices.

Firefox for Android WebKit iOS (Safari/Chrome/Firefox)
Firefox for Android screen shot Firefox for iOS screenshot

A simple tel input

In its most basic form, a tel input can be implemented like this:

<label for="telNo">Phone number:</label>
<input id="telNo" name="telNo" type="tel">

There is nothing magical going on here. When submitted to the server, the above input’s data would be represented as, for example, telNo=+12125553151.

Placeholders

Sometimes it’s helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn’t offer descriptive labels for each <input>. This is where placeholders come in. A placeholder is a value that demonstrates the form the value should take by presenting an example of a valid value, which is displayed inside the edit box when the element’s value is "". Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears.

Here, we have an tel input with the placeholder 123-4567-8901. Note how the placeholder disappears and reappears as you manipulate the contents of the edit field.

<input id="telNo" name="telNo" type="tel"
       placeholder="123-4567-8901">

Controlling the input size

You can control not only the physical length of the input box, but also the minimum and maximum lengths allowed for the input text itself.

Physical input element size

The physical size of the input box can be controlled using the size attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the tel edit box is 20 characters wide:

<input id="telNo" name="telNo" type="tel"
       size="20">

Element value length

The size is separate from the length limitation on the entered telephone number. You can specify a minimum length, in characters, for the entered telephone number using the minlength attribute; similarly, use maxlength to set the maximum length of the entered telephone number.

The example below creates a 20-character wide telephone number entry box, requiring that the contents be no shorter than 9 characters and no longer than 14 characters.

<input id="telNo" name="telNo" type="tel"
       size="20" minlength="9" maxlength="14">

Примечание: The above attributes do affect Validation — the above example’s inputs will count as invalid if the length of the value is less than 9 characters, or more than 14. Most browser won’t even let you enter a value over the max length.

Providing default options

As always, you can provide a default value for an tel input box by setting its value attribute:

<input id="telNo" name="telNo" type="tel"
       value="333-4444-4444">

Offering suggested values

Taking it a step farther, you can provide a list of default phone number values from which the user can select. To do this, use the list attribute. This doesn’t limit the user to those options, but does allow them to select commonly-used telephone numbers more quickly. This also offers hints to autocomplete. The list attribute specifies the ID of a <datalist> element, which in turn contains one <option> element per suggested value; each option‘s value is the corresponding suggested value for the telephone number entry box.

<label for="telNo">Phone number: </label>
<input id="telNo" name="telNo" type="tel" list="defaultTels">

<datalist id="defaultTels">
  <option value="111-1111-1111">
  <option value="122-2222-2222">
  <option value="333-3333-3333">
  <option value="344-4444-4444">
</datalist>

With the <datalist> element and its <option>s in place, the browser will offer the specified values as potential values for the email address; this is typically presented as a popup or drop-down menu containing the suggestions. While the specific user experience may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested email addresses. Then, as the user types, the list is adjusted to show only filtered matching values. Each typed character narrows down the list until the user makes a selection or types a custom value.

Here’s a screenshot of what that might look like:

Validation

As we’ve touched on before, it’s quite difficult to provide a one-size-fits-all client-side validation solution for phone numbers. So what can we do? Let’s consider some options.

Предупреждение: Important: HTML form validation is not a substitute for server-side scripts that ensure the entered data is in the proper format before it is allowed into the database. It’s far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It’s also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database.

Making telephone numbers required

You can make it so that an empty input is invalid and won’t be submitted to the server using the required attribute. For example, let’s use this HTML:

<form>
  <div>
    <label for="telNo">Enter a telephone number (required): </label>
    <input id="telNo" name="telNo" type="tel" required>
    <span class="validity"></span>
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>

And let’s include the following CSS to highlight valid entries with a checkmark and invalid entries with a cross:

div {
  margin-bottom: 10px;
  position: relative;
}

input[type="number"] {
  width: 100px;
}

input + span {
  padding-right: 30px;
}

input:invalid+span:after {
  position: absolute; content: '✖';
  padding-left: 5px;
  color: #8b0000;
}

input:valid+span:after {
  position: absolute;
  content: '✓';
  padding-left: 5px;
  color: #009000;
}

The output looks like this:

Pattern validation

If you want to further restrict entered numbers so they also have to conform to a specific pattern, you can use the pattern attribute, which takes as its value a regular expression that entered values have to match.

In this example we’ll use the same CSS as before, but our HTML is changed to look like this:

<form>
  <div>
    <label for="telNo">Enter a telephone number (in the form xxx-xxx-xxxx): </label>
    <input id="telNo" name="telNo" type="tel" required
           pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
    <span class="validity"></span>
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
div {
  margin-bottom: 10px;
  position: relative;
}

input[type="number"] {
  width: 100px;
}

input + span {
  padding-right: 30px;
}

input:invalid+span:after {
  position: absolute; content: '✖';
  padding-left: 5px;
  color: #8b0000;
}

input:valid+span:after {
  position: absolute;
  content: '✓';
  padding-left: 5px;
  color: #009000;
}

Notice how the entered value is reported as invalid unless the pattern xxx-xxx-xxxx is matched; for instance, 41-323-421 won’t be accepted. Neither will 800-MDN-ROCKS. However, 865-555-6502 will be accepted. This particular pattern is obviously only useful for certain locales — in a real application you’d probably have to vary the pattern used depending on the locale of the user.

Examples

In this example, we present a simple interface with a <select> element that lets the user choose which country they’re in, and a set of <input type="tel"> elements to let them enter each part of their phone number; there is no reason why you can’t have multiple tel inputs.

Each input has a placeholder attribute to show a hint to sighted users about what to enter into it, a pattern to enforce a specific number of characters for the desired section, and an aria-label attribute to contain a hint to be read out to screenreader users about what to enter into it.

<form>
  <div>
    <label for="country">Choose your country:</label>
    <select id="country" name="country">
      <option>UK</option>
      <option selected>US</option>
      <option>Germany</option>
    </select>
  </div>
  <div>
    <p>Enter your telephone number: </p>
    <span class="areaDiv">
      <input id="areaNo" name="areaNo" type="tel" required
             placeholder="Area code" pattern="[0-9]{3}"
             aria-label="Area code">
      <span class="validity"></span>
    </span>
    <span class="number1Div">
      <input id="number1" name="number1" type="tel" required
             placeholder="First part" pattern="[0-9]{3}"
             aria-label="First part of number">
      <span class="validity"></span>
    </span>
    <span class="number2Div">
      <input id="number2" name="number2" type="tel" required
             placeholder="Second part" pattern="[0-9]{4}"
             aria-label="Second part of number">
      <span class="validity"></span>
    </span>
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>

The JavaScript is relatively simple — it contains an onchange event handler that, when the <select> value is changed, updates the <input> element’s pattern, placeholder, and aria-label to suit the format of telephone numbers in that country/territory.

var selectElem = document.querySelector("select");
var inputElems = document.querySelectorAll("input");

selectElem.onchange = function() {
  for(var i = 0; i < inputElems.length; i++) {
    inputElems[i].value = "";
  }

  if(selectElem.value === "US") {
    inputElems[2].parentNode.style.display = "inline";

    inputElems[0].placeholder = "Area code";
    inputElems[0].pattern = "[0-9]{3}";

    inputElems[1].placeholder = "First part";
    inputElems[1].pattern = "[0-9]{3}";
    inputElems[1].setAttribute("aria-label","First part of number");

    inputElems[2].placeholder = "Second part";
    inputElems[2].pattern = "[0-9]{4}";
    inputElems[2].setAttribute("aria-label","Second part of number");
  } else if(selectElem.value === "UK") {
    inputElems[2].parentNode.style.display = "none";

    inputElems[0].placeholder = "Area code";
    inputElems[0].pattern = "[0-9]{3,6}";

    inputElems[1].placeholder = "Local number";
    inputElems[1].pattern = "[0-9]{4,8}";
    inputElems[1].setAttribute("aria-label","Local number");
  } else if(selectElem.value === "Germany") {
    inputElems[2].parentNode.style.display = "inline";

    inputElems[0].placeholder = "Area code";
    inputElems[0].pattern = "[0-9]{3,5}";

    inputElems[1].placeholder = "First part";
    inputElems[1].pattern = "[0-9]{2,4}";
    inputElems[1].setAttribute("aria-label","First part of number");

    inputElems[2].placeholder = "Second part";
    inputElems[2].pattern = "[0-9]{4}";
    inputElems[2].setAttribute("aria-label","Second part of number");
  }
}

The example looks like this:

This is an interesting idea, which goes to show a potential solution to the problem of dealing with international phone numbers. You would have to extend the example of course to provide the correct pattern for potentially every country, which would be a lot of work, and there would still be no foolproof guarantee that the users would enter their numbers correctly.

It makes you wonder if it is worth going to all this trouble on the client-side, when you could just let the user enter their number in whatever format they wanted on the client-side and then validate and sanitize it on the server. But this choice is yours to make.

div {
margin-bottom: 10px;
position: relative;
}

input[type="number"] {
  width: 100px;
}

input + span {
  padding-right: 30px;
}

input:invalid+span:after {
  position: absolute; content: '✖';
  padding-left: 5px;
  color: #8b0000;
}

input:valid+span:after {
  position: absolute;
  content: '✓';
  padding-left: 5px;
  color: #009000;
}

Specifications

Browser compatibility

BCD tables only load in the browser

See also

В последнее время нельзя пренебрегать кликабельными номерами телефонов т.к. количество клиентов, использующих мобильные телефоны превысило десктопы. И чтобы не потерять своего клиента, необходимо предоставить посетителю возможность беспрепятственно позвонить.

1

Оформление ссылки tel

По умолчанию на мобильных телефонах номера телефона распознается автоматически и преобразуются в ссылки.

До:

<div class=phone>+7 (495) 123-45-67</div>

HTML

После:

<div class=phone><a href="tel:+74951234567">+7 (495) 123-45-67</a></div>

HTML

Чтобы задать нормальные стили на мобильных, нужно писать два правила.

.phone {
	color: #000;
	font-size: 16px;
	font-weight: 900;
}
.phone a {
	color: #000;
	font-size: 16px;
	font-weight: 900;
}

CSS

Или по атрибуту:

a[href^="tel:"] {
	color: #000;
	font-size: 16px;
	font-weight: 900;
}

CSS

2

Отключить распознавание телефонов

Автоматическое распознавание телефонов работает не всегда корректно и срабатывает на большие цены. Его можно отключить, добавив метатег в <head> страницы и прописать ссылки у телефонов вручную.

<meta name="format-detection" content="telephone=no">

HTML

3

Оборачивание телефонов ссылками

Замечена одна особенность – на андроид устройствах не всегда срабатывает клик по ссылке если в атрибуте href форматированный номер телефона.

<!-- Рабочая ссылка -->
<a href="tel:+74951234567">+7 (495) 123-45-67</a>

<!-- Нерабочая -->
<a href="tel:+7 (495) 123-45-67">+7 (495) 123-45-67</a>

HTML

4

Обвернуть телефон регулярным выражением

Если телефонов много, то лучше автоматизировать замену с помощью регулярного выражения.

function replace_phone_call($matches)
{
	$tel = str_replace(array('-', ' ', '(' , ')'), '', $matches[0]);
	$tel = str_replace('+7', '8', $tel);
	return '<a href="tel:' . $tel . '">' . $matches[0] . '</a>';
}
 
function replace_phone($text)
{
	return preg_replace_callback('/(?:+|d)[d-() ]{9,}d/', 'replace_phone_call', $text);
}
 
$text = 'Позвоните по телефону +7 (495) 123-45-67, или 88001234567';
echo replace_phone($text);

PHP

Результат:

Позвоните по телефону <a href="tel:84951234567">+7 (495) 123-45-67</a>, 
или <a href="tel:88001234567">88001234567</a>

Также можно добавить проверку мобильных с помощью mobiledetect и на десктопе ссылки не выводить.

require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
define('IS_MOBILE', $detect->isMobile() && !$detect->isTablet());

function replace_phone_call($matches)
{
	$tel = str_replace(array('-', ' ', '(' , ')'), '', $matches[0]);
	$tel = str_replace('+7', '8', $tel);
	return '<a href="tel:' . $tel . '">' . $matches[0] . '</a>';
}
 
function replace_phone($text)
{
	if (IS_MOBILE) {
		return preg_replace_callback('/(?:+|d)[d-() ]{9,}d/', 'replace_phone_call', $text);
	} else {
		return $text;
	}
}
 
$text = 'Позвоните по телефону +7 (495) 123-45-67, или 88001234567';
echo replace_phone($text);

PHP

Или сделать на мобильных ссылку с номером телефона, а на десктопе ссылку на форму обратного звонка.

require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
define('IS_MOBILE', $detect->isMobile() && !$detect->isTablet());

function replace_phone_call($matches)
{
	if (IS_MOBILE) {
		$tel = str_replace(array('-', ' ', '(' , ')'), '', $matches[0]);
		$tel = str_replace('+7', '8', $tel);
		return '<a href="tel:' . $tel . '">' . $matches[0] . '</a>';		
	} else {
		return '<a class="modal" href="/callbaсk">' . $matches[0] . '</a>';	
	}
}
 
function replace_phone($text)
{
	return preg_replace_callback('/(?:+|d)[d-() ]{9,}d/', 'replace_phone_call', $text);
}
 
$text = 'Позвоните по телефону +7 (495) 123-45-67, или 88001234567';
echo replace_phone($text);

PHP

Результат на десктопе и планшетах:

Позвоните по телефону <a class="modal" href="/callbak">+7 (495) 123-45-67</a>, 
или <a class="modal" href="/callbak">88001234567</a>

На мобильных:

Позвоните по телефону <a href="tel:84951234567">+7 (495) 123-45-67</a>, 
или <a href="tel:88001234567">88001234567</a>

Приветствую вас, дорогие друзья на сайте Impuls-Web!

На сегодняшний день, ввиду того, что количество пользователей, которые используют для просмотра сайтов мобильные устройства, постоянно растет, стало очень популярным размещение на страницах сайта кликабельных ссылок на телефонные номера.

Ссылка на телефон HTML дает возможность посетителю сайта, в случае, если его заинтересовало ваше предложение, сразу же позвонить по данному номеру и сделать заказ на приобретение товара или услуги.

В этой статье я покажу вам, как сделать ссылку на телефон HTML, а так же покажу, как можно ее оформить при помощи CSS.

Протокол HTML5 для ссылок на телефон

Для того чтобы сделать ваш телефонный номер кликабельным его необходимо обернуть в тег <a>…</a> и в атрибуте href указать протокол tel и через двоеточие указать номер без пробелов и дефисов:

<a href=«tel:0955414642»>0955414642</a>

Теперь клик по данной ссылке на телефон HTML будет восприниматься любым браузером на любом мобильном устройстве как команда к набору данного номера.

Показанную выше запись удобно использовать чтобы принимать заявки от посетителей с мобильных устройств. Но дело в том, что оформленная в таком виде ссылка на телефон HTML будет вызывать неудобство у тех пользователей, которые зашли на ваш сайт с компьютера. При клике по такой ссылке на ПК, в зависимости от браузера, будет выпадать ошибка, либо будет открываться для набора номера Skype или какая-то другая программа. Вряд ли кто-то из пользователей захочет позвонить вам на телефонный номер по Skype и такая функция, скорее всего, отпугнет клиента.

Для решения данной проблемы есть очень интересный скрипт. Но его использование немного затруднит добавление ссылки на телефон HTML.

  1. 1.На странице там, где вам нужно разместить телефонный номер, вставляем пустой блок с уникальным идентификатором. В моем случае phone-link:

    <div id=«phone-link»></div>

  2. 2.Открываем страницу для редактирования в NotePad++ или его аналоге и перед закрытием тега </body> вставляем скрипт:

    <script>

    if( /BlackBerry|iPhone|iPod|iPad|Android|IEMobile|webOS|Opera Mini/i.test(navigator.userAgent) ) {

      document.getElementById(«phone-link»).innerHTML = ‘<span><a href=»tel:0955414642 «>(095)541-46-42</a></span>’;

    } else {

      document.getElementById(«phone-link»).innerHTML = ‘<span>(095)-541-46-42</span> ‘;

    }

    </script>

    Данный скрипт проверяет, с какого устройства открыта станица вашего сайта и автоматически подставляет нужный вариант телефонного номера. Если пользователь просматривает страницу с мобильного телефона, то будет подставлена ссылка на телефон HTML. Если же пользователь открыл страницу с ПК, то будет подставлен телефон обернутый в тег <span>.

В случае если у вас сайт сделан на CMS, то вам нужно открыть для редактирования файл, в котором закрывается тег . Например, в WordPress это происходит в файле footer.php.

Как работать в редакторе кода NotePad++ вы можете прочитать в этой статье: Редактирование файлов сайта в Notepad++

Так же обратите внимание на тот момент, что при использовании данного скрипта у вас по факту будут для ПК и для мобильных устройств отображаться разные варианты отображения ссылки на телефон HTML. Соответственно вам необходимо предусмотреть два варианта стилизации. Для ПК вам нужно будет добавить стили для <span>, а для мобильной версии стили нужно писать для ссылки, то есть для тега а.

Сами стили оформления могут быть идентичными. То есть при написании CSS стилей вы даже можете совместить селекторы для сокращения кода. Вот как это будет выглядеть, если вы будете использовать мой вариант скрипта, и мой ID блока:

#phone-link span, #phone-link a{

}

Для мобильного варианта можно также добавить стили при наведении не ссылку:

Другие варианты протоколов HTML5

Кроме телефона вы можете таким же образом оформить и другие контактные данные для своего сайта. Вам доступны для использования следующие протоколы:

  • callto – вызов контакта Skype
  • mailto – для e-mail адреса
  • fax – для отправки факса
  • sms – отправка SMS-сообщения

Данные протоколы используются точно так же, как и протокол tel. Например:

<a href=«mailto:ask@my-mail.ru»>Задавайте вопросы по электронной почте</a>

Так же для данных протоколов актуальна проблема восприятия для браузеров на ПК. Поэтому приведенный выше скрипт так же актуален.

Сделав для своего сайта такие ссылки на телефон HTML, вы существенно повысите удобство пользования сайтам для ваших посетителей и, вероятно, это поможет вам увеличить количество заказов с сайта. Очень надеюсь, что данный прием оформления телефона будет для вас полезен.

А на сегодня у меня все. Не забывайте делиться статьей в социальных сетях и оставлять комментарии!

До встречи в следующих статьях!

С уважением Юлия Гусарь

Когда пользователь может в один клик по номеру телефона сделать звонок, это в плюс и ему, и вам. Он тратит минимум усилий и времени, чтобы вам дозвониться, а вы получаете +1 целевой звонок. Естественно, это относится к мобильным устройствам.

В этой статье мы покажем, как сделать кликабельный номер телефона на сайте. Алгоритмы отличаются в зависимости от того, на чем создан ваш сайт.

HTML-код

Обычный номер телефона, который пока является простым текстом, в коде может выглядеть так:

<span>+7(999)888-77-66</span>

Или так (если присвоен класс):

<p class=»phone”>+7(999)888-77-66</p>

Или так (если к этому тексту применены стили: цвет, шрифт, форматирование):

<div id=»number» class=»phone mobile text num» style=»color: #1f21ff; text-align: center» name=»phone_number»>+7(999)888-77-66</p>

За гипертекст (возможность текста в коде HTML включать в себя гиперссылку) отвечает тег <a>…</a>. Атрибут href=”” отвечает за то, куда будет направлен клиент — внутри кавычек указывается адрес страницы или действие.

За автоматический набор номера по клику отвечает параметр tel:ХХХ, где XXX — номер телефона без пробелов и тире.

Таким образом, для первого примера код будет следующим:

<span>

<a href=”tel:+79998887766”>+7(999)888-77-66</a>

</span>

К тексту добавили действие – вызов на конкретный номер.

Сделаем и второй номер кликабельным:

<p class=»phone”>

<a href=”tel:+79998887766”>+7(999)888-77-66</a>

</p>

Третий пример тоже без особых усилий становится гипертекстом. При этом сохраняются его изначальные стили:

<div id=»number» class=»phone mobile text num» style=»color: #1ff1ff; text-align: center» name=»phone_number»>

<a href=”tel:+79998887766”>+7(999)888-77-66</a>

</p>

По этому же принципу вы можете сделать кликабельный email.

Чтобы email стал кликабельным, поставьте атрибут <a href=”mailto:XXX”>.

Сайт на WordPress

Для Вордпресса есть специальный плагин CallPhone’r. Этот модуль выводит на каждой странице сайта иконку, при нажатии на которую мобильное устройство переходит в режим вызова.

Кликабельный номер телефона – плагин CallPhone’r на WordPress

Там же есть возможность настройки по времени отображения иконки. Это позволит не получать звонки от клиентов в нерабочее время.

Сайт на mottor (LPmotor)

Этот конструктор дает несколько вариантов.

1) Телефон в виде текста.

В этом случае выделите текст телефона в блоке и нажмите кнопку добавления ссылки в панели редактирования:

Кликабельный номер телефона – копирование номера на LPmotor

2) Переход к набору номера с кнопки. В панели редактирования блока «Кнопка» необходимо выставить «Переход по ссылке» и указать ваш номер телефона в формате «tel:88005555555».

Кликабельный номер телефона – добавление номера для кнопки на LPmotor

3) Переход к набору номера с иконки/картинки. Здесь в выпадающем меню «Действие» нужно выбрать «Переход по ссылке» и вставить номер в формате «tel:+74957873422».

Кликабельный номер телефона – добавление номера для картинки на LPmotor

4) Также можно вставить кликабельный телефон на сайт в виде html блока.

Тогда в поле «Редактирование HTML-кода» нужно вставить

<a href=»tel:+74957873422″>Позвонить 8 (495) 787 34 22</a>.

Кликабельный номер телефона – редактирование HTML-кода на LPmotor

Сайт на Wix

1) Чтобы создать кликабельный номер телефона:

— Добавьте текст. Вот инструкция из базы знаний Wix о том, как это сделать;

— Нажмите «Редактировать текст»;

— Введите номер телефона. Не вводите другой текст в том же окне.

Кликабельный номер телефона – создание кликабельного номера в Wix

2) Чтобы связать текст ссылкой с номером телефона:

— Добавьте текст;

— Нажмите «Редактировать текст»;

— Введите текст, например, «Позвонить сейчас»;

— Выделите текст;

— Нажмите на иконку «Ссылка»;

— Выберите Номер телефона;

— Введите номер телефона в поле «Номер телефона»;

— Нажмите «Готово».

Кликабельный номер телефона – привязка текста ссылкой к номеру телефона в Wix

3) Чтобы связать кнопку ссылкой с номером телефона:

— Добавьте кнопку

— Измените текст кнопки

— Нажмите на иконку Ссылка

— Выберите Номер телефона

— Введите номер телефона в поле «Номер телефона»

— Нажмите «Готово».

Кликабельный номер телефона – привязка кнопки ссылкой к номеру телефона в Wix

Сайт на Tilda

Чтобы при клике на номер телефона начинался звонок или при клике на e-mail открывался почтовый клиент, нужно навесить на них ссылки.

1) Ссылка, которую нужно задать тексту с номером телефона: tel:+71234567890 (все без пробела). Будет работать при просмотре сайта на телефоне.

Например, выбираете блок меню ME301, во вкладке Контент в поле Дополнительно указываете номер телефона, затем выделяете его и с помощью выпадающей панели инструментов для текста добавляете ссылку вида tel:+7123456789.

2) Ссылка, которую нужно задать тексту с адресом почты: yourmail@mysite.com. При добавлении ссылки в Контент блока в поле «Ссылка», нужно указывать ссылку как mailto:yourmail@mysite.com.

Как отслеживать клики по номеру телефона

Это можно делать без вмешательства в код и установки Менеджера тегов Google. В Яндекс.Метрике не так давно появился новый тип цели – «Клик по номеру телефона». Достаточно указать нужные параметры, и данные о звонках будут поступать в Метрику:

Кликабельный номер телефона – добавление цели «Клик по номеру телефона»

Чтобы всё работало, важно указать номер в точности такой же, какой указан в коде сайта. Лучше всего скопировать адрес ссылки прямо с сайта. Для этого:

  • Кликните правой кнопкой мыши по номеру на сайте и нажмите в меню «Просмотреть код»;
  • В открывшейся консоли разработчика вы увидите нужную ссылку с номером;

Кликабельный номер телефона – ссылка с номером телефона для Метрики

  • Скопируйте её и вставьте в параметрах цели.

Кликабельный номер телефона – добавление номера телефона для отслеживания кликов

Данные по кликам на номер телефона появятся в отчете «Конверсии» уже через несколько минут после создания цели.

Хотите тоже написать статью для читателей Yagla? Если вам есть что рассказать про маркетинг, аналитику, бизнес, управление, карьеру для новичков, маркетологов и предпринимателей. Тогда заведите себе блог на Yagla прямо сейчас и пишите статьи. Это бесплатно и просто

Telephone links are the ones that you tap to call a number on phone-capable devices. Of course, some devices are able to recognize phone numbers and provide the linking automatically, but it’s not always so.

In the example below, we use :tel within the HTML <a> tag. Note that tel: is much like a protocol, and not a feature.

Example of adding a telephone link:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
  </head>
  <body>
    <a href="tel:+05890000111">0-589-0000111</a>
  </body>
</html>

Result

There isn’t any documentation (official) on this protocol handler for links. That’s why there can be differences in browser support and behavior. Commonly, browsers make different decisions on determining what to do with the clicked link.

You can use a little CSS to style your telephone link. Let’s see an example where we add color to our link with the CSS color property.

Example of adding color to the telephone link:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      a {
        color: #ff2121;
        text-decoration: none;
      }
    </style>
  </head>
  <body>
    <a href="tel:+05890000111">0-589-0000111</a>
  </body>
</html>

In our next example, we’ll add a phone character before the telephone number with the CSS ::before pseudo-element and content property.

Example of adding a phone character before the telephone link:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      a[href^="tel:"]:before {
        content: "260e";
        margin-right: 10px;
      }
    </style>
  </head>
  <body>
    <a href="tel:+05890000111">0-589-0000111</a>
  </body>
</html>

На сегодняшний день большинство мобильных устройств с браузером также являются телефонами! Так почему бы не создавать для телефонных номеров на вашей странице ссылки, кликая по которым вызывалось бы встроенное приложене для звонков. Если вы создаете сайт бизнес руководства, консалтингового агенства или просто продаете пирожки на своем сайте, большинство людей предпочтут позвонить вам в 1-2 тача вместо нудного заполнения формы (особенно на мобильном девайсе).

Мы уже писали об URI-схемах для отправки смс тут.

Первым стандартом, де-факто (скопированным с японских I-MODE стандартов) является использование tel: схемы. Он был предложен в качестве стандарта в RFC 5341, но будьте осторожны, потому что большинство предложенных там параметров не работают на всех устройствах.

Сегодня поддержка tel: URI-схемы есть почти в каждом мобильном устройстве, в том числе в Safari на IOS, Android Browser, WebOS Browser, Symbian браузер, Internet Explorer, Opera Mini и т.п.

Очень простой и лаконичный синтаксис:

html

<a href="tel:+1234567890"> Звоните нам бесплатно! </ a>

href=”tel:…”

Если пользователь кликает по такой ссылке, мобильное приложение попросит подтверждения вызова с указанием полного номера. Это позволит избежать мошенничества или обмана пользователя при звонках в другую страну или на премиум-номер.

На десктопе, с установленным Skype (или подобным софтом), система попросит вас подтвердить открытие внешнего приложения, при клике на такую ссылку.

Я рекомендую указывать телефонный номер в международном формате: знак плюс (+), код страны, код местной зоны и номер абонента. Мы ведь иногда действительно не знаем, где наши посетители физически расположены. Если они находятся в той же стране, или даже в том же районе, международный формат также будет работать.

Существуют, также другие варианты которые вы можете встретить. Давайте посмотрим несколько примеров для ознакомления, просто что-бы знать, что такое бывает. Но я не рекомендовал-бы использовать их из-за различий в поддержке браузерами.

html

<a href="callto:12345678">Работает на iPhone и Nokia</a>
<a href="wtai://wp/mc;12345678">Работает на Android</a>
<a href="wtai://wp/mc;+123456789">международный формат для Android</a>

В целом все, что хотелось сказать. Используйте tel: URI-схемы и будет вам счастье ;)

Понравилась статья? Поделить с друзьями:
  • Твц номер телефона
  • Тег html для номера телефона
  • Тебриз астрахань доставка шашлыка номер телефона бабаевского
  • Тебердинский заповедник номер телефона
  • Тебе дать мой номер телефона