How to Show and Hide Adsense Ads from your HTML5 Canvas Game

These days, Google Adsense allows you to show and hide their adds in your dynamic web content using a combination of your HTML5 canvas, javascript, and CSS. Using a couple simple tricks, you can display an advertisement in your games homescreen for example, and then hide it when your user is playing the game. This allows you to use Adsense, but avoid your game becoming too cluttered with ads while still monetizing it.

The first thing you should do is create your Adsense ad and wrap it with a CSS div. You now have an HTML item that you can show and hide using Javascript functions. Here is an example CSS div I created to wrap an Adsense ad that always shows the 728 pixel leaderboard in the bottom center of the user's screen:

		#desktop-ad {
			display: block;
			background: #000;
			margin-left: -364px;
			width: 728px;
			height: 90px;
			position: absolute;
			bottom: 0px;
			left: 50%;
			z-Index: 1000;
			border: 1px solid #fff;		

Now, in the

of your html file, you will need the Javascript functions that show and hide your Adsense element. These functions don't get much simpler. There is one function that hides your element and another that displays it. It is displayed as a CSS block, which works for most applications, you may want to change it to inline or whatever you need.
	<script type="text/javascript" language="JavaScript"><!--
		function HideContent(d) {
			document.getElementById(d).style.display = "none";
		function ShowContent(d) {
			document.getElementById(d).style.display = "block";

At this point, you have your adsense ad in your HTML document and the Javascript functions to show and hide it as needed. Now, the last step is to have your HTML5 canvas game or application show and hide your ad as needed! From within your game's Javascript, here are some example function calls that show and hide the ad if at the homescreen:

//Desktop Ad
if(homescreen) {
	//Show Ad
//Desktop Ad
if(!homescreen) {
	//Hide Ad