Move init function caller?

I have created an HTML 5 canvas presentation in Adobe Animate CC. I have successfully moved the canvas element and all of its supporting js files to my own webpage. It is currently working and displaying the animation. I had to insert an

<body onload="init();">

into my body tag. When my HTML page first opens the area where this canvas element is located is not visible. I think it would be optimal if I could run this init function when my page scrolls to that area of the page. Could someone tell me how to accomplish this? Thanks

Define ‘not visible’ a little better for me.
Not visible as in it’s actually HIDDEN, or not visible as in “It’s too far down the page on my screen” (Note that your screen is subjective - different resolutions/orientations will show more/less of your webpage.)

Traditionally this would have been achieved with a scroll event listener… along the lines of

var whenInViewport = function (target, callback) {
  window.addEventListener('scroll', function handleScroll (event) {
    if (target.getBoundingClientRect().top < window.innerHeight) {
      callback(event)
      window.removeEventListener('scroll', handleScroll)
    }
  })
}

whenInViewport(document.getElementById('my-target'), init)

However this is quite expensive… you may get away with only that single one and debouncing or throttling the scroll handler. Better would be using an intersection observer though:

var whenInViewport = function (target, callback) {
  var observer = new IntersectionObserver(function (entries) {
    entries.forEach(function (entry) {
      if (entry.target === target && entry.isIntersecting) {
        callback(entry)
        observer.unobserve(target)
      }
    })
  })

  observer.observe(target)
}

Unfortunately this API is not supported by IE though, so you’ll need a polyfill for this.

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