Freeze scroll script for popups

Just posting this for my own future use cause I can’t decide where I should keep my notes. If it helps you then good on ya!

You’ll need the Toolbox and Classify plugin of course.

Setup, best to put in your app’s body script

<script>
    var scrollPos;

    function freezeElement(elementId,mainDivId) {
        var element = document.getElementById(elementId);
        var mainDiv = document.getElementById(mainDivId);
        
        scrollPos = window.scrollY;
        
        element.setAttribute("data-scroll-position", scrollPos); // save original scroll position
        element.style.position = "fixed";
        element.style.top = -scrollPos + "px";
        element.style.left = "0px";
        element.style.height = window.innerHeight + "px";
        mainDiv.style.height = window.innerHeight + "px";
        
        document.body.scrollIntoView({ behavior: 'smooth', block: 'start' }); // smooth scroll to top of page
    }

    function unfreezeElement(elementId,mainDivId) {
        var element = document.getElementById(elementId);
        var mainDiv = document.getElementById(mainDivId);
        element.style.position = "";
        element.style.top = "";
        element.style.left = "";
        element.style.height = "";
        mainDiv.style.height = "";
        window.scrollTo(0, scrollPos); // return to original scroll position
    }
</script>

To use just call the function freezeElement(“nameOfElementIDToFreeze”,“pageElementID”) when a popup opens and unfreezeElement(“nameOfElementIDToFreeze”,“pageElementID”) when the popup closes.

Add this Class to popup to ensure there’s no weird gap at the top:

.poptop {
  top: 25px !important;
}
3 Likes