jQuery: showing and hiding ads

Ads (advertisements) are a fundamental component of many web sites. In this post I'm going to discuss with you a way to dynamically show such ads using jQuery. You only have to know the basics of CSS absolute positioning and a couple of jQuery effects. First, let's start with our basic markup:

<div id="ads">
 <div><!--ads contents go here--></div>
<div id="site">
 <!--site contents go here-->

We want our ads appear just two seconds after the site has finished loading. As you can see, I've directly embedded the ads container within the markup. Sure, you could do this with jQuery, but you will probably notice the unwanted effect of the ads container first shown and then hidden again. This happens because JavaScript is loaded after the HTML structure and the CSS styles.

For that reason, we're going to use CSS to hide our ads:

body {
 margin: 0;
 padding: 0;
 font: 62.5% Arial, sans-serif;
 position: relative;

#ads {
 height: 100px;
 background: #333 url(fade.jpg) repeat-x;
 color: #fff;
 line-height: 100px;
 position: absolute;
 top: 0;
 left: 0;
 width: 100%;
 text-align: center;
 font-size: 4em;
 text-transform: uppercase;
 display: none;
 cursor: pointer;
 letter-spacing: 0.1em;

#ads div {
 background: url(close-button.png) no-repeat 65% 50%;
 height: 100%;
 width: 100%;

Our ads container has been absolutely positioned at the very top of our page and then hidden using display: none. In this case, using this declaration doesn't cause accessibility problems, because ads are something that is not crucial for understanding the contents of our site.

Note that you can put whatever you want in this container, including Google AdSense and other advertising snippets. Now we can use jQuery. First, we wait two seconds before showing our ads:

$(document).ready(function() {

  setTimeout(function() {
  }, 2000);
  // continues

We've used the setTimeout() function here. Then we want to allow users to close the ads container by clicking on it:

// continues
$('#ads').click(function() {

You can see the demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.