0

I'm building a Wordpress site with Ajaxify to create smooth transition between pages.

In my custom template page-about.php I have a JS script to create a sticky horizontal scroll. The script works fine. But when I change page by navigating on the AJAX site. It releases the following error:

TypeError: null is not an object (evaluating 'sticky.offsetTop')

Here is the JS script:

 if ($('.wrapper-horizontal').length) {
      const spaceHolder = document.querySelector('.space-holder');
      const horizontal = document.querySelector('.horizontal');
      spaceHolder.style.height = `${calcDynamicHeight(horizontal)}px`;

      function calcDynamicHeight(ref) {
        const vw = window.innerWidth;
        const vh = window.innerHeight;
        const objectWidth = ref.scrollWidth;
        return objectWidth - vw + vh + 150;
       }

        window.addEventListener('scroll', () => {
            const sticky = document.querySelector('.is-sticky-h');
            horizontal.style.transform = `translateX(-${sticky.offsetTop}px)`;
        });

        window.addEventListener('resize', () => {
            spaceHolder.style.height = `${calcDynamicHeight(horizontal)}px`;
        });
        //# sourceURL=pen.js
  }

I tried this solution but it doesn't work in my case:

    document.addEventListener('readystatechange', function() {
        if (document.readyState === "complete") {
          // Do something
      }
    });

Any help would be much appreciated. Thanks!

Mathieu Préaud
  • 147
  • 1
  • 11
  • The **only** reason `querySelector` returns `null` is if no element was found in the DOM when you called it that matched the selector. In this case, that means there was no element in the DOM with the class `is-sticky-h` when `const sticky = document.querySelector('.is-sticky-h');` was executed. We can't tell you why that is based on the information in the question, but that's what the error is telling you. 99% of the time it's a timing thing (the code is running earlier than you expected, and the element hasn't been created yet), though sometimes of course it's a typo. – T.J. Crowder Mar 23 '21 at 12:01
  • Thanks. I thought using `$('.wrapper-horizontal').length()` would prevent it. So how can I trigger the JS script only when `.wrapper-horizontal` exists in the DOM? – Mathieu Préaud Mar 23 '21 at 12:05
  • You probably want that check within the event handlers, not just at setup time. But it really depends a lot on the greater context. – T.J. Crowder Mar 23 '21 at 12:08
  • It did the trick, thank you very much! – Mathieu Préaud Mar 23 '21 at 12:15

0 Answers0