Home > Back-end >  How to animate a button when it is visible for the user by scrolling
How to animate a button when it is visible for the user by scrolling

Time:01-16

When you scroll on a page, the page shows an element, I want to be able to specify this element and do code with it using JS, is this possible? I tried something but it had another problem..

What I tried was,

let section = document.getElementById('out');
window.onscroll = function() {
if (window.scrollY >= 678) {
document.getElementById('out').style.color = "red";
} else {
document.getElementById('out').style.color = "black"
}
}

I didn't use animate here, I just made sure it works, and it did, well almost, because if you zoom in/out it ruins it, I think that's because I got the 678 by going to the button and printing scrollY manually, is there anyway to make that automatic, so it works on any element I need? I searched a lot and can't seem to find what I need, the solutions need jQuery, I need a solution only with html, css, and javascript.

CodePudding user response:

In the future the solution will be css scroll timelines, but as that feature is at the time of writing experimental and is not supported by major browsers you can use intersection observers.

Quoted from MDN:

The Intersection Observer API lets code register a callback function that is executed whenever an element they wish to monitor enters or exits another element (or the viewport), or when the amount by which the two intersect changes by a requested amount.

To animate a component when it is in or out of view, you can give animated elements a .hidden class in your html markup and create an intersection observer which appends the .shown class to .hidden elements when they are in view.

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => entry.target.classList.toggle(“shown”, entry.isIntersecting))
})

const hiddenElements = document.querySelectorAll(“.hidden”)
hiddenElements.forEach((el) => observer.observe(el))

Then you can just apply transitions under a <selector>.shown css rule.

  • Related