Coding with Jesse

Let people turn off ads Part 2

August 13rd, 2006

As I warned yesterday, I've put ads back on the site. Currently, I only have them on the individual blog post pages (the pages that have comments on them). If you only read from the home page, or if you read via RSS, you won't see them.

I also walked my own talk by letting people turn off the ads if they wish. I did it entirely with JavaScript, so I thought I'd share my methodology with you.

The HTML just looks like this:

<div class="ads">
    <script type="text/javascript" src="banner-ad.js"></script>
</div>

And the JavaScript in banner-ad.js looks like this:

/* Customized Google Adsense codes */
google_ad_client = "pub-3809601305027895";
google_ad_width = 468;
google_ad_height = 60;
google_ad_format = "468x60_as";
google_ad_type = "text";
google_ad_channel ="8087340205";
google_color_border = "99bbee";
google_color_bg = "99bbee";
google_color_link = "000000";
google_color_url = "000000";
google_color_text = "000000";

/* cookie functions from QuirksMode */
function setCookie (name,value,days) {
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie (name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

/* onclick function to remove ads */
function removeAds() {
    /* set a cookie for 10 years to stop showing ads */
    setCookie('hideads', '1', 365*10);

    /* hide every div on the page with the class name 'ads' */
    var ads = document.getElementsByTagName('div');
    for (var i=0;i < ads.length;i++) {
        if (ads[i].className == 'ads') {
            ads[i].style.display = 'none';
        }
    }

    return false;
}

/* don't show the ads if the cookie is there */
if (getCookie('hideads') != '1') {
    /* write out the link to hide the ads */
    document.write('<a href="#" onclick="return removeAds()">Remove Ads</a>');

    /* write out the regular Adsense script tag */
    document.write('<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>');
}

When the 'Remove Ads' link is clicked, the ads are instantly hidden using CSS and a cookie is set. Next time this script is loaded, as long as the cookie is set, the ads won't be written to the page anymore.

About the author

Jesse Skinner Hi, I'm Jesse Skinner. I'm a self-employed web developer with over two decades of experience. I love learning new things, finding ways to improve, and sharing what I've learned with others. I love to hear from my readers, so please get in touch!