Vanilla JavaScript example
Lookup user's country
Overview
For the best user experience, the library 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, set initialCountryLookup to a function that makes the IP lookup request and returns a Promise resolving to the iso2 code. The library 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. If the request fails, the returned promise should reject (or resolve with an empty/invalid value) so the library falls back appropriately.
Note: the toast shown when input is rejected isn't part of the library — see the strict:reject event docs for an example of how to wire one up yourself.
Demo
Html
<label for="phone">Phone number</label>
<input id="phone" type="tel">
JavaScript
initialCountryLookup here uses ipapi's free tier. For production, swap for a paid plan or alternative - see docs.import intlTelInput from "intl-tel-input";
const input = document.querySelector("#phone");
const initialCountryLookup = async () => {
const res = await fetch("https://ipapi.co/json");
const data = await res.json();
return data.country_code;
};
intlTelInput(input, {
initialCountryLookup,
loadUtils: () => import("/intl-tel-input/js/utils.js"),
});