JavaScript plugin example

Lookup user's country

For the best user experience, the plugin supports setting the initial selected country to the user's current country, using an IP lookup service. When the user first sees the input, they already see the correct flag and a familiar placeholder number for their country.

To achieve this, enable two initialisation options:

  1. Set initialCountry to "auto". This tells the plugin to use the IP lookup service.
  2. Set geoIpLookup to a function that makes the IP lookup request and returns the iso2 code. The plugin will then use that iso2 code to set the initial country.

In the example below, we call the ipapi service (which offers a free tier) using the standard fetch API. Note that the failure callback inside geoIpLookup must be called in the event of an error — hence the use of catch in the example code.

Demo

Html

<label for="phone">Phone number</label>
<input id="phone" type="tel">

JavaScript

geoIpLookup here uses ipapi's limited free tier — for production, pick a paid plan, another provider, or roll your own.
import intlTelInput from "intl-tel-input";

const input = document.querySelector("#phone");
intlTelInput(input, {
  initialCountry: "auto",
  separateDialCode: true,
  strictMode: true,
  strictRejectAnimation: true,
  geoIpLookup: (success, failure) => {
    fetch("https://ipapi.co/json")
      .then(res => res.json())
      .then(data => success(data.country_code))
      .catch(() => failure());
  },
  loadUtils: () => import("/intl-tel-input/js/utils.js"),
});