JavaScript

Search for '{{search_term}}'

Show ads to visitors based on referrer using JavaScript only

CMOS is the Code-Maven Open Source podcast that also includes video interviews. Subscribe to this feed RSS feed with your Podcast listener app or via iTunes iTunes.

You might want to treat visitors to your site differently based on where they came from. Especially if they came from another page on the same site. You can easily achieve this using some JavaScript code and looking at the referrer.

examples/js/ads_to_selected_visitors.html

<h1>Title</h1>

<div id="ad_code_maven">
Internal visitor arriving from another Code-Maven page.
</div>
<div id="ad_others">
This is shown to people arriving from outside of th Code-Maven site.
</div>



<p>
Text.
</p>


<script>	
console.log(document.referrer);
console.log(document.referrer.split('/')[2]);

if (document.referrer.split('/')[2] === 'code-maven.com') { 
    document.getElementById('ad_code_maven').style.display = 'block'; 
    document.getElementById('ad_others').style.display = 'none'; 
} else {
    document.getElementById('ad_code_maven').style.display = 'none'; 
    document.getElementById('ad_others').style.display = 'block'; 
}
</script>
Try!

In most browsers the attribute document.referrer contains the page that was visited earlier. It is normally set by the browser wen you click on a link or when you are somehow forwarded from one page to another.

If you type in a new URL in the address bar and press ENTER them this attriibute will be empty.

We can use this attribute to identify which other site and which page sent the visitor to us. We can use the full value in document.referrer or we can extract part of if. For example document.referrer.split('/')[2] will extract the domain name.

We can then locate an HTML element using getElementById and the id of the element and we can set the display attribute to either 'none' to remove the element from the DOM and make it disappear, or we can set it to 'block' to show it. (We could also set it to 'inline' if you'd like to show it in the same line as another element. There are a few additional values it can take, but these are the most common.

In our code example we have two div elements. One of them is shown to 'internal visitors', the others to everyone else. Of course, you could use similar conditions to show specific message to people coming from Google or from any other site.

Comments

In the comments, please wrap your code snippets within <pre> </pre> tags and use spaces for indentation.
comments powered by Disqus