JS to reposition elements when they leave the viewport?

I’m looking for a way to reposition elements on the bottom-right of the viewport once the elements are scrolled out of the viewport from their original position.

I can’t find an example at the moment, but this is common with video ads and also blog posts that have embedded video/audio players.

For example, suppose I have an embedded Youtube Video/Soundcloud. It’s positioned by default at the top of the page. But, once the the user scrolls down the viewport, after the media player element is

I’m a noobie, but the best thing I can come up with is to pass the height of the media player and then add the scroll listener to position:fixed the media player element once they’ve scrolled down enough.

What’s the best way to tackle this?

You might look up a snippet of JS code for “lazy loading” images, as this is essentially the test in the opposite direction. It would give you a jump start on what you want to do. Basically, grab the bounding box around your video, see if it’s viewable on the screen, and if not, move it somewhere else.

Hi @jeremy58, a more modern approach (no IE support, naturally) would be using an intersection observer; for instance, you might toggle a CSS class like so:

const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
      entry.intersectionRatio < 1
}, { threshold: [0, 1] })

  .forEach(player => observer.observe(player))

If you just want to make the element sticky though, you might look into use position: sticky instead (no IE support, naturally).

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.