Dynamically Inserting Google Adsense Ads Into A Page Using jQuery

Google's in-article Adsense ads are a nice way to deliver ads to visitors within the content of your pages. Depending on your page's structure, you might want to display an ad after the 4th paragraph or div on a page.
To do this via jQuery, you will first need to make a variable containing your ad information using the "ins" code provide by Adsense:

Adsense:

var adsense = '<ins class="adsbygoogle" style="display:block; text-align:center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-xxxxxxxxxxxxxxxx" data-ad-slot="xxxxxxxxxx"></ins>';
Next, we'll tell jQuery to place the ad ("adsense") after the 4th div within the parent div ("#content").

jQuery:

jQuery('#content > div:eq(4)').after(adsense);
And include the Adsense scripts after that:

Adsense:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script>
The final code will look like this:
<script> var adsense = '<ins class="adsbygoogle" style="display:block; text-align:center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-xxxxxxxxxxxxxxxx" data-ad-slot="xxxxxxxxxx"></ins>'; jQuery('#content > div:eq(4)').after(adsense); </script> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script>
If you need to make ad placement conditional based on how many divs are available, have jQuery count the number of divs located with the parent container ("#content"). In this example, we're asking that the ad only be inserted if the content contains more than 3 divs.
// Count the number of divs within #content container var div = $('#content').children('div').length; // Display it in the console for debug if needed console.log("divs = "+div); // If there are more than 3 divs, display the ad after the 4th div located with the #content container if (div > 3) { jQuery('#content > div:eq(4)').after(adsense); }

Sticky Side Column

If you're using our PHP Website Template, this is the optional side bar column you can add to some or all of your pages. It can be useful for adding advertisements such as Adsense ads to be displayed on multiple pages.
When you include the side column, your main content will automatically adjust its width to accommodate it.
The side bar is 'sticky'; it will scroll down and remain in view.
You can turn on/off the side bar column per page by defining the $showSide option located at the top of each file.