0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DFP 広告枠がスクロールで画面外にいったらリロードする

Last updated at Posted at 2018-02-06

縦長ページでスクロールしていて広告枠が上下どちらかの画面外に切れたらその広告枠をリロードし、スクロールアップなどで再びその広告枠を見た時は新しい広告を表示

<script>
	googletag.cmd.push(function() {
		var lastScrollTop = 0;
		var slot = googletag.defineSlot('/XXXXXX/REC_300x250', [[300, 250]], 'dfpad').addService(googletag.pubads());
		googletag.pubads().enableSingleRequest();
		googletag.pubads().disableInitialLoad();
		googletag.enableServices();
		googletag.display('dfpad');
		googletag.pubads().refresh([slot]);
		window.addEventListener("scroll", isScrolledIntoView, false);
		function isScrolledIntoView() {
		    var rect = document.getElementById('dfpad').getBoundingClientRect();
		    var st = window.pageYOffset || document.documentElement.scrollTop;
		    //スクロール方向によって挙動を変える
		    if (st > lastScrollTop){
		    	var elemBottom = rect.bottom;
			    if (elemBottom < 0 && elemBottom > -100) {
			    	//発火の範囲は100px内に
			    	googletag.pubads().refresh([slot]);
			    }
		    } else {
		    	var elemTop = rect.top;
			    if (window.innerHeight < elemTop && elemTop < (window.innerHeight + 100)) {
			    	//発火の範囲は100px内に
			    	googletag.pubads().refresh([slot]);
			    }
		    }
		    lastScrollTop = st;
		}
	});
</script>
<div id="dfpad"></div>
0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?