1

I'm building a portfolio website with React with large full width vertically scrolling images. There is a single text box on the side of the webpage that I would like to display the title of each image as each image comes into view.

Any recommendations on how to change the text in a DIV when an image comes into view? I'm not even sure what to search to find an answer to this. Any help is much appreciated. Thanks!

Mike R
  • 11
  • 1
  • This answer might help, you should be able to modify the styles to fit your needs [https://stackoverflow.com/questions/29725828/update-style-of-a-component-onscroll-in-react-js](https://stackoverflow.com/questions/29725828/update-style-of-a-component-onscroll-in-react-js) – miyu Mar 22 '19 at 07:04
  • Could you share your current HTML structure? So I could make a solution that will fit your current code. Or you could just use the link miyu gave. – boosted_duck Mar 22 '19 at 07:19

1 Answers1

0

You can attach an onscroll listener to detect when the user scrolls. Inside the listener, you need to do some math to calculate which element is currently viewed. The variables you can use for the calculation are scrollTop (on the container, used to determine the current scroll position) and the clientHeight of each element.

let nameDisplayDiv = document.getElementById('display')
let containerDiv = document.getElementById('container')

function refresh() {
  let scrollTop = containerDiv.scrollTop + containerDiv.clientHeight / 2
  let height = 0
  for (let child of containerDiv.children) {
    let top = height
    let bottom = height += child.clientHeight
    if (top < scrollTop && bottom > scrollTop) {
      // Found the element that's currently viewed!
      nameDisplayDiv.innerHTML = child.style.backgroundColor
      break
    }
  }
}

containerDiv.onscroll = refresh

Here's a working fiddle: https://jsfiddle.net/uxh91Leq/2/

Viktor W
  • 1,139
  • 6
  • 9