Search code examples
javascriptgoogle-mapsgoogle-places-autocomplete

How to Append google auto complete inside modal


I am trying to add Google autocomplete places inside modal popup, but the issue I am facing is that it appends to body instead of modal, is there any way we can append it inside modal? Codepen Example

enter image description here

Reason: when modal opens, it scrolls set to hidden same as Bootstrap modal, and when "Auto Complete" is append to body it changes it's position while scrolling

kindly see below:

enter image description here

Is there a way to fix this problem, any help will be appreciated.

Thanks


Solution

  • The google autocomplete gets appended to the HTML Body tag and from there it traces the position of the specified input serach box.

    You can add a scroll event listener on the #myModal element and then trace the position of the input #pac-input.

    Add the following code after the initAutocomplete function.

    const modal = document.getElementById("myModal");
    modal.onscroll = function(e) {
        const pacContainer = document.querySelector(".pac-container.pac-logo");
        let top = window.scrollY + document.getElementById("pac-input").getBoundingClientRect().top;
        pacContainer.style.top = `${top + 25}px`;
    }
    

    here on scroll of the #myModal HTML element, its calulating the top position of #pac-input and adding 25px (Assumed height of input) to the google autocomplete div.