How to call a modal when scrolling to the desired block?

  • 0
    Hello! The page has a block with id = "popup", and there is also a modal window with a form and id = "exampleModal". How to make this window open as soon as the user scrolls the page to the block with id = "popup"?
    JavaScript Lorelei Klein, Nov 9, 2020

  • 1 Answers
  • 0
    Depending on the required browser support, you have 2 options.

    1 - more versatile, but more manual work:

    When loading a document, find your element with id = popup in the tree. Save to variable.

    Add a scroll handler to the document and check the current scroll and the position of the element above the beginning of the document ( tyk and tyk ). Matches - call the modal.

    2 is more modern, but the browser will do everything for you:

    Use Intersection Observer

    The essence is, in general, the same. Indicate which element to watch, indicate what to watch for the appearance of this element in the viewport and indicate the function of the handler of this event, in which you open the modal.

    Here is some sample code on Intersection observer

    var options = {
    root: null, // Не указываем = следим за областью вьюпорта.
    rootMargin: '0px', // отступы вокруг root
    threshold: 1.0
    var callback = function(entries, observer) {
    // Открываем модалку
    var observer = new IntersectionObserver(callback, options);

    /* Параметр threshold со значением 1.0 означает что функция будет вызвана при 100% пересечении объекта (за которым мы следим) с объектом root */

    var target = document.querySelector('#popup'); // элемент, за которым будем следить.


Your Answer
To place the code, please use CodePen or similar tool. Thanks you!