Site logo

Archived topic

Make Element Appear After Scroll

3 replies · Started by lerschiboi on February 7, 2023

Viewing posts 1–4 of 4

Hi,

I've created a sticky "See Buying Options" Block Element that sticks to the bottom of my sales page: https://nutriciously.com/fall-winter-meal-plan/

Now, I'd like for this element to not be visible immediately but to fade in after the user has scrolled for a bit.

I tried this code from David over here: https://generatepress.com/forums/topic/bottom-sticky-works-now-want-to-load-on-scroll/ but it doesn't seem to work for me. I targeted the page in question and chose wp_footer as the hook.

From what I understand, this should add the class "show-me" to my element after scrolling, which I can then use to make the element appear with some CSS. Is that correct and what do I have to do to make this work?

Thanks!

Hi there,

try this script:


<script>
// debounce scroll eventListener
function debounceX(func, wait = 10, immediate = true) {
  let timeout;
  return function() {
    let context = this, args = arguments;
    let later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    let callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};
// check position 
function checkScrollPosition() {
  let windowY = window.scrollY;
  let targetY = 600; // target scroll position
  if (windowY < targetY) {
    watchedEL.classList.remove('is-visible');
  } else {
    watchedEL.classList.add('is-visible');
  }
  scrollPos = windowY;
}
//  add listener
const watchedEL = document.querySelector('#see-buying-options');
window.addEventListener('scroll', debounceX(checkScrollPosition));
</script> 

Set the let targetY = 600; // target scroll position to how far scrolling in pixels before it gets displayed

That script will toggle the is-visible class on the element.
So you can use some CSS like this:

#see-buying-options {
    opacity: 0; 
    pointer-events: none;
    transition: all 0.3s ease-in;
}
#see-buying-options.is-visible {
    opacity: 1;
    pointer-events: auto;
}

As a fallback in case the user has disabled JS on their device.
Add this script to your site too:

<noscript>
    <style type="text/css">
    #see-buying-options.is-visible {
      opacity: 1 !important;
      pointer-events: auto !important;
    }
    </style>
</noscript>

It will make sure the button is visible in that scenario.

Oh my goodness, that worked like a charm. Thanks David, you're the best! :)

Glad to be of help!

This archived topic is closed to new replies.