Skip to content

Intersection observer #285

@HEAVYPOLY

Description

@HEAVYPOLY

How would you set up an intersection observer with vanJS? I have gallery of image thumbnails and would like to dynamically load/unload them when they come into view with intersection observer

const GalleryThumb = (canvas) => {
  // let imageArrayBuffer = getLatestAsset(canvas.id, 'image')
  // const image = URL.createObjectURL(imageBlob)
  const Thumb = () => div(
    {
      id: `galleryThumb${canvas.id}`,
      class: 'galleryThumb',
      'data-clicked': 'false',
      onclick: (e) => galleryThumbInput(e, this, canvas.id),
    },
    canvas.id?.slice(0, 4),
    div({
      class: 'image',
      style: `background-image:url(${canvas.thumbnail})`,
      loading: 'lazy',
    }),
    div({ class: 'hoverable deleteButton hidden' }),
    div({ class: 'hoverable playButton hidden' }),
    div({ class: 'hoverable restoreButton hidden' })
  )
  galleryObserver.observe(Thumb)

  return Thumb
}

let galleryObserver = false

function setupGalleryObserver () {
  const options = {
    root: galleryUI, // observing intersections relative to the viewport
    rootMargin: '900px', // margin around the root
    threshold: 0.1 // callback is executed when at least 10% of the target is visible
  }

  const callback = (entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        prnt('INTERSECTING')
      } else {
        if (isVisible(galleryUI)) {
          entry.target.classList.add('loadingStatic')
          freeImage(entry.target.thumbnail)
        }
        prnt('NOT INTERSECTING')
      }
    })
  }
  galleryObserver = new IntersectionObserver(callback, options)
}

galleryObserver.observe(Thumb) throws TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions