Pragmatic Web Media

How to Refresh the Ads based on the Viewability and Timer?

There are multiple methods to refresh ad slots. Refreshing ad slots helps in increasing the volume of the site and revenue but it has some limitation on some prospective. Important factor need to consider while refreshing ad slot is “Viewability”. This metric determines ad revenue because all advertisers want to show ads to real user. If the user not in viewable area, refreshing ad slot negatively impact the ad revenue. So the best practice is always refresh ads only when the user in active viewable area.

How to do that?

Need to define a custom coding on the site along with the GPT.

What kind of code it is?. I’m not an developer.

It is a Simple JavaScript code. You can use our code. It is like a plug and play.

Is this works only for one Ad?

No, Script is designed in a way to validate the name of the DIV. As long as DIV id contain that string. It will work for all.

Make sure DIV id is mentioned correctly on the query selector “document.querySelectorAll(‘div[id^=”div-gpt”]’);” on the script.

Summary of coding Logic.

Working example with Sample codes

Tagging workflow with GPT tags

  1. Define Header tags on the head of your site.
  2. Add body tag after <body>
  3. Add a custom script on the body of the site
  4. Add a Refresh function on the “function startViewTimer(id)”.
  5. Adjust “viewTime == 10” seconds on the script based on the requirement

Live implementation

Here is the code which implemented on the test page.

https://pragmaticwebmedia.github.io/Refresh-based-on-Viewability-and-Timer/

Complete code with all GPT tags


<html>
  <head>
    <title>Viewable Time Tracker</title>
    <style>
      #div-gpt-div-1 {
        height: 250px;
        width:300px;
        background-color: #f080f0;
        margin-bottom: 50px;
      }

      #div-gpt-div-2 {
        height: 250px;
        width:300px;
        background-color: #90d0d0;
      }
    </style>
    <script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
<script>
  window.googletag = window.googletag || {cmd: []};
   var slot1;
  googletag.cmd.push(function() {
   slot1 = googletag.defineSlot('/200894144/Responsive', [[300, 250], [300, 600]], 'div-gpt-ad-1620832289302-0').setTargeting("Test_Mode", "ON").addService(googletag.pubads());
    
        googletag.enableServices();
  });
</script>
  </head>
  <body>
    <div id="div-gpt-div-1"></div>
    <div id="div-gpt-div-2"></div>
    <div id='div-gpt-ad-1620832289302-0'>
<script>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-1620832289302-0');
});
</script>
</div>

    <script>
      var divs = document.querySelectorAll('div[id^="div-gpt"]');
      var timers = {};

      function isInView(elem) {
        var bounding = elem.getBoundingClientRect();
        return (
          bounding.top >= 0 &&
          bounding.left >= 0 &&
          bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
          bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
      }

      function startViewTimer(id) {
        timers[id] = {
          viewTime: 0,
          intervalID: setInterval(function() {
            if (isInView(document.getElementById(id))) {
              timers[id].viewTime += 1;
              console.log('Viewable time for ' + id + ':', timers[id].viewTime, 'seconds');
              if (timers[id].viewTime == 10) {
                alert('You have viewed the ' + id + ' div for 10 seconds!');
                googletag.pubads().refresh([slot1]);
              }
            } else {
              timers[id].viewTime = 0;
            }
          }, 1000)
        };
      }

      function stopViewTimer(id) {
        clearInterval(timers[id].intervalID);
        delete timers[id];
      }

      for (var i = 0; i < divs.length; i++) {
        var div = divs[i];
        var id = div.getAttribute('id');
        startViewTimer(id);
      }

      document.addEventListener('visibilitychange', function() {
        if (document.visibilityState === 'hidden') {
          for (var id in timers) {
            stopViewTimer(id);
          }
        } else {
          for (var i = 0; i < divs.length; i++) {
            var div = divs[i];
            var id = div.getAttribute('id');
            if (timers[id]) {
              clearInterval(timers[id].intervalID);
              timers[id].viewTime = 0;
            }
            startViewTimer(id);
          }
        }
      });
    </script>
  </body>
</html>

Explanation for each function used on the script.

  1. isInView(elem): This function takes an element as an argument and returns a boolean indicating whether the element is currently visible in the viewport. It does this by checking the element’s bounding rectangle against the viewport’s dimensions.
  2. startViewTimer(id): This function starts a timer for the specified element ID. It sets an interval function to run every second, which increments a viewTime counter for the element if it is currently visible in the viewport. If the viewTime counter reaches 10 seconds, an alert is displayed. The function stores the interval ID and the viewTime counter for the element in the timers object.
  3. stopViewTimer(id): This function stops the timer for the specified element ID. It clears the interval and removes the element’s data from the timers object.
  4. DOMContentLoaded: This event fires when the initial HTML document has been completely loaded and parsed. In this script, we use it to query the page for all div elements, and start a timer for each element ID that matches the specified pattern.
  5. visibilitychange: This event fires when the page’s visibility state changes (e.g. the user switches tabs, minimizes the window, etc.). In this script, we use it to stop all timers if the page is no longer visible, and restart them when it becomes visible again. If a timer was already running when the page became invisible, it resets its viewTime counter to 0 when it restarts.

Hope this post helps you and save your time. Please support ,ask question and suggest topics for more articles.

Thank you !!!!!!

*The information contained in this post is for general information purposes only. The information is provided by How to Refresh the Ads based on the Viewability and Timer? and while we endeavor to keep the information up to date and correct, we make no representations or warranties of any kind, express or implied, about the completeness, accuracy, reliability, suitability or availability with respect to the website or the information, products, services, or related graphics contained on the post for any purpose.

Exit mobile version