Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // рабочая версия до добавления интернациональной версии
- const API_KEY = "37f3cb2a937f495ca93b3c4ae1b62ad4";
- const API_URL = "https://ipgeolocation.abstractapi.com/v1/";
- const RESERVE_API_URL = "https://ipapi.co/json/";
- // список стран с переводом названий
- const COUNTRIES = [{"code":"ru","translation":"Россия"},{"code":"ua","translation":"Украина"},{"code":"ge","translation":"Грузия"},{"code":"tm","translation":"Туркменистан"},{"code":"am","translation":"Армения"},{"code":"by","translation":"Белоруссия"},{"code":"uz","translation":"Узбекистан"},{"code":"az","translation":"Азербайджан"},{"code":"kz","translation":"Казахстан"},{"code":"md","translation":"Молдавия"},{"code":"tj","translation":"Таджикистан"},{"code":"kg","translation":"Киргизия"}];
- // локализация стран
- const LOCALIZED_COUNTRIES = COUNTRIES.reduce((cv, pv) => { cv[pv["code"]] = pv["translation"]; return cv }, {});
- // показывать только эти страны
- const ONLY_COUNTRIES = COUNTRIES.map(country => country.code);
- // вынос некоторых стран вверх списка
- const PREFFERED_COUNTRIES = ["ru", "ua"];
- // селекторы для привязки к ним событий дропдауна (PHONEINPUTS) и заполнения поля полного телефона при отправке (FULLPHONES / SENDBUTTONS)
- const PHONEINPUTS = ["#phone-input-1", "#phone-input-2", "#phone-input-3", "#phone-input-4", "#phone-input-5", "#phone-input-6"];
- const FULLPHONES = ["#phone-full-1", "#phone-full-2", "#phone-full-3", "#phone-full-4", "#phone-full-5", "#phone-full-6"];
- const SENDBUTTONS = ["#send-button-1", "#send-button-2", "#send-button-3", "#send-button-4", "#send-button-5", "#send-button-6"];
- // настройки
- const PLUGIN_PROPERTIES = {
- initialCountry: "auto",
- onlyCountries: ONLY_COUNTRIES,
- localizedCountries: LOCALIZED_COUNTRIES,
- preferredCountries: PREFFERED_COUNTRIES,
- separateDialCode: true,
- geoIpLookup: geoIpLookup
- };
- const PLUGIN_INSTANCES = {
- "1": null,
- "2": null,
- "3": null,
- "4": null,
- "5": null,
- "6": null
- }
- PHONEINPUTS.forEach((input, idx) => {
- // hack for maskedinput and cursor disabling can work :(
- const _PHONEINPUT_ = $(input);
- const PHONEINPUT = document.querySelector(input);
- const SENDBUTTON = document.querySelector(SENDBUTTONS[idx]);
- // ставим маску на все поля
- _PHONEINPUT_.mask("(999) 999-99-99?");
- // отключаем курсор во всех полях
- disableCursorInInput(_PHONEINPUT_);
- // инициализируем плагин на каждом из input'ов
- PLUGIN_INSTANCES[idx + 1] = window.intlTelInput(PHONEINPUT, PLUGIN_PROPERTIES);
- // вешаем обработчик события смены страны на каждый input
- PHONEINPUT.addEventListener("countrychange", function() {
- const countryCode = PLUGIN_INSTANCES[idx + 1].getSelectedCountryData().iso2;
- const dialCode = PLUGIN_INSTANCES[idx + 1].getSelectedCountryData().dialCode;
- setCookie("clientcountry", countryCode);
- changeCountryInAllForms(PLUGIN_INSTANCES, idx + 1, countryCode, PHONEINPUT);
- });
- // вешаем обработчик на каждую кнопку каждой формы для собирания
- // в кучу кода страны + номера (чтобы убрать лишнее скрытое поле)
- SENDBUTTON.addEventListener("click", function(e) {
- // TODO: REMOVE (FOR DEVELOPMENT NEEDS)
- e.preventDefault();
- console.log("SENDBUTTON clicked");
- //
- PHONEINPUT.value = "+" + PLUGIN_INSTANCES[idx + 1].getSelectedCountryData().dialCode + " " + PHONEINPUT.value, "PHONEINPUT value";
- });
- });
- // функция отвечающая за отключение курсора
- function disableCursorInInput(selector) {
- $(selector).click(function() {
- $(this)[0].selectionStart = $(this)[0].selectionEnd = 0;
- });
- }
- // функция для получения куки
- function getCookie() {
- const cookie = document.cookie.split("; ").map(cookie => ({ "name": cookie.split("=")[0], "value": cookie.split("=")[1] })).filter(cookie => cookie.name === "clientcountry");
- return cookie.length > 0 ? cookie[0].value : null
- }
- // функция для установки куки
- function setCookie(name, value) {
- document.cookie = `${name}=${value}`;
- return true;
- }
- // функция отвечающая в плагине за автоматическое определение страны
- function geoIpLookup(success, failure) {
- const clientCountryCookie = getCookie("clientcountry");
- if(clientCountryCookie !== null) {
- success(clientCountryCookie);
- // TODO: check number of requests before cookie used
- // console.log("country defined by cookie");
- } else {
- fetch(API_URL + "?&api_key=" + API_KEY)
- .then(r => r.json())
- .then(info => {
- var countryCode = info && info.country_code ? info.country_code.toLowerCase() : "ru";
- setCookie("clientcountry", countryCode);
- success(countryCode);
- })
- .catch(e => {
- console.log("error getting ip adress by main API --> trying to get from reserve API");
- reserveGeoIpLookup(success, failure);
- })
- }
- }
- // функция для резервного определения страны по IP
- function reserveGeoIpLookup(success, failure) {
- fetch(RESERVE_API_URL)
- .then(r => r.json())
- .then(info => {
- var countryCode = info && info.country_code ? info.country_code.toLowerCase() : "ru";
- setCookie("clientcountry", countryCode);
- success(countryCode);
- })
- .catch(e => {
- console.log("error getting ip adress by reserve API --> setting defaults to 'ru'");
- success("ru");
- })
- }
- // смена страны во всех инпутах
- function changeCountryInAllForms(pluginInstancesObject, currentInstanceIdx, countryCode) {
- for (instance in pluginInstancesObject) {
- pluginInstancesObject[instance].setCountry(countryCode);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment