0

I'm trying to run a group of ads that lazy load, so they are only visible when the user scrolls down to the part of the page the ads are supposed to be. I have a function that does what I need when I click on the div, but the user is not going to click where this div is. My code is:

export const handleAds = items => {
  if (!items) return

  for (let i = 0; i < items.length; i++) {

    items[i].addEventListener('click', getAds, {
        once: true
      }
    )
  }

  function getAds() {
    const placeholder = document.querySelector('[ad-placeholder]')

    if (placeholder) {
      placeholder.classList.remove('hidden')
      placeholder.classList.add('flex')
    }

    (function() {
      var sc = document.createElement('script'); sc.type = 'text/javascript'; sc.async = true;
      sc.src = '//myads.media/data/js/somescript.js'; sc.charset = 'utf-8';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(sc, s);
    })()
  }


}

The ads are at the bottom of the page just above the page footer. Thus, mouse over is not an option. The user could be using the arrow buttons or the mouse scroll wheel when the cursor is not over the part of the page where the divs are. Therefore, I need it to load when the div is visible. How can I achieve this?

AviG
  • 350
  • 1
  • 10

2 Answers2

1

If you want to track css attributes you can check this answer.

Event listener for when element becomes visible?

  • i don't want the ads even loading until I get to the right part of the page; I'm not simply gonna have them invisible or set to color #ffffff – AviG Aug 09 '19 at 20:37
  • Then Olegs answer might work for you. Create an scroll event listener, compare windows position with that part of page, then call your code. – Ömer Faruk Kırlı Aug 09 '19 at 20:44
  • this is for lazy loading – AviG Aug 11 '19 at 00:23
  • I can get it to work now with the Intersection Observer, but when I scroll away, the div goes away. I only want it done one time if the div is seen. How can I do that? – AviG Aug 11 '19 at 19:12
  • You can keep it in a boolean variable for each div. An array would work for this case. You can make specific indexed element (maybe just last one) true if div had seen and check if it is true or not. If true then dont call your call otherwise call it. It may be a little complicated but there is nothing more i can say without seeing all code. – Ömer Faruk Kırlı Aug 12 '19 at 21:55
0

Well you can get current position of the window object. Get window.screenY and the element offset bottom. If those two match, load the ads (ofcourse attach it to scroll listener).