diff --git a/src/scripts/choices.js b/src/scripts/choices.js index 0525525..246b7c0 100644 --- a/src/scripts/choices.js +++ b/src/scripts/choices.js @@ -1954,7 +1954,7 @@ class Choices { this.choiceList.clear(); if (this.config.resetScrollPosition) { - this.choiceList.scrollToTop(); + requestAnimationFrame(() => this.choiceList.scrollToTop()); } // If we have grouped options diff --git a/src/scripts/components/input.js b/src/scripts/components/input.js index 91ed36c..096f3e9 100644 --- a/src/scripts/components/input.js +++ b/src/scripts/components/input.js @@ -95,16 +95,20 @@ export default class Input { this.element.value.length >= this._placeholderValue.length / 1.25) || enforceWidth ) { - this.element.style.width = this.calcWidth(); + this.calcWidth(width => { + this.element.style.width = width; + }); } } else { // If there is no placeholder, resize input to contents - this.element.style.width = this.calcWidth(); + this.calcWidth(width => { + this.element.style.width = width; + }); } } - calcWidth() { - return calcWidthOfInput(this.element); + calcWidth(callback) { + return calcWidthOfInput(this.element, callback); } setActiveDescendant(activeDescendantID) { diff --git a/src/scripts/components/input.test.js b/src/scripts/components/input.test.js index dc24c28..928ba02 100644 --- a/src/scripts/components/input.test.js +++ b/src/scripts/components/input.test.js @@ -269,7 +269,7 @@ describe('components/input', () => { const inputWidth = '200px'; beforeEach(() => { - calcWidthStub = stub(instance, 'calcWidth').returns(inputWidth); + calcWidthStub = stub(instance, 'calcWidth').callsArgWith(0, inputWidth); }); afterEach(() => { diff --git a/src/scripts/lib/utils.js b/src/scripts/lib/utils.js index 412ea99..b12aec7 100644 --- a/src/scripts/lib/utils.js +++ b/src/scripts/lib/utils.js @@ -227,10 +227,10 @@ export const strToEl = (function() { }()); /** - * Sets the width of a passed input based on its value - * @return {Number} Width of input + * Determines the width of a passed input based on its value and passes + * it to the supplied callback function. */ -export const calcWidthOfInput = (input) => { +export const calcWidthOfInput = (input, callback) => { const value = input.value || input.placeholder; let width = input.offsetWidth; @@ -259,14 +259,18 @@ export const calcWidthOfInput = (input) => { document.body.appendChild(testEl); - if (value && testEl.offsetWidth !== input.offsetWidth) { - width = testEl.offsetWidth + 4; - } + requestAnimationFrame(() => { + if (value && testEl.offsetWidth !== input.offsetWidth) { + width = testEl.offsetWidth + 4; + } - document.body.removeChild(testEl); + document.body.removeChild(testEl); + + callback.call(this, `${width}px`); + }); + } else { + callback.call(this, `${width}px`); } - - return `${width}px`; }; /**