jackocnr / intl-tel-input

A JavaScript plugin for entering and validating international telephone numbers. Now includes React and Vue components.
https://intl-tel-input.com
MIT License
7.57k stars 1.94k forks source link

Padding issue when initialise with separateDialCode on hidden input #909

Closed jackocnr closed 5 years ago

jackocnr commented 5 years ago

Originally posted by @crabnky in https://github.com/jackocnr/intl-tel-input/issues/885#issuecomment-487786957

20190430_015555

Originally posted by @mac89 in https://github.com/jackocnr/intl-tel-input/issues/885#issuecomment-496980252

https://codepen.io/mac89/pen/gJJBLR

This issue is caused when the element is hidden when the plugin is initialized causing the offsetWidth to be 0.

My proposed solution is this:

var el = this.telInput;
while ((el = el.parentElement) && !el.classList.contains("intl-tel-input"));
var clone = el.cloneNode(true);
clone.style.visibility = "hidden";
document.body.appendChild(clone);

var selectedFlagClone = clone.getElementsByClassName("selected-flag").index(0);
var offsetWidth = selectedFlagClone ? selectedFlagClone.offsetWidth : 0;

// add 6px of padding after the grey selected-dial-code box, as this is what we use in the css
this.telInput.style.paddingLeft = "".concat(offsetWidth + 6, "px");
mac89 commented 5 years ago

You want me to create a new pull request?

jackocnr commented 5 years ago

Thanks very much for reporting this bug and creating the codepen. Unfortunately I find the proposed solution to be too complicated, as this is an edge case IMO.

Can I ask: why do you need to initialise the plugin before you show the input? Wouldn't it be better to just initialise it after you show it?

mac89 commented 5 years ago

I'm using JQuery Mobile and when a page is loaded by it through ajax, the content (including your plugin initialization) is first rendered before the page is actually shown. I'd have to listen for a pageshow event every time I want to include a tel input and there is the possibility that the input would look off during the page transition.

jackocnr commented 5 years ago

Ok then I am open to a PR, but with a few changes:

Thanks very much.

mac89 commented 5 years ago
jackocnr commented 5 years ago

the loop is required in cases where the input gets wrapped by another plugin

If you have other plugins that are manipulating the markup around the input then you should make sure those get run before you intialise this plugin else you will get styling problems as this plugin's container really needs to be the parent of the input element.

So I have merged your PR (thank you so much), but I have removed that loop code in a followup.