AviG
AviG

Reputation: 392

I can get my script to run when the user clicks on the correct div, but how can I get it to run when the div simply becomes visible on the browser?

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?

Upvotes: 0

Views: 37

Answers (2)

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

Event listener for when element becomes visible?

Upvotes: 1

Poselsky
Poselsky

Reputation: 65

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).

Upvotes: 0

Related Questions