Show/Hide Element when parent div hits top of viewport

Hi,

Is it possible to show or hide a child div when its parent div hits the top of the viewport using Cwicly settings. I tried to follow the back to top tutorial here: (43) Back To Top Button in WordPress Gutenberg - YouTube.

But i have still not been able to get it to work because the div i want to show/hide should not have a link action and also shouldn’t have it’s position set to absolute.

Any help will be greatly appreciated. Thanks.

@Louis please any pointers for this?

Hi @zagency,

We currently have Scroll Interactions for page specific positions (top, bottom), but not relative positions of a block within the viewport.

This would require a small JS function to add a class (or whatever necessary in your case) to the parent/target block.

You could use this small snippet in a Code block (quick mockup, needs refining):

// get the element you want to add/remove the class from
const element = document.querySelector(".yourclass");

// create a function to add/remove the class
function toggleClass() {
  const topPosition = element.getBoundingClientRect().top;
  if (topPosition <= 0) {
    element.classList.add("top-viewport");
  } else {
    element.classList.remove("top-viewport");
  }
}

// attach the function to the scroll event
window.addEventListener("scroll", toggleClass, { passive: true });

@Louis Thanks for this. Worked perfectly.

1 Like