I have a site which shows an ad banner upon page load. I'd like for it to also change while someone is viewing the site, maybe after a few minutes?
This is my current code which displays the initial banner using PHP:
$path = '/images/adbanners/';
$banners = array(
array( 'src' => 'look.jpg',
'href' => 'http://www.example.com/look'),
array( 'src' => 'see.jpg',
'href' => 'http://www.example.com/see'),
array( 'src' => 'horse.jpg',
'href' => 'http://www.example.com'),
array( 'src' => 'scg.png',
'href' => 'https://www.example.com/scg/'),
array( 'src' => 'karen.png',
'href' => 'http://www.example.com/'karen),
);
$rnd = mt_rand(0,count($banners)-1); // Pick a random array index. They start with 0, so you have to -1.
$href = $banners[$rnd]['href']; // Link HREF
$src = $path.$banners[$rnd]['src']; // Image source
$randombanner = '<a href="'.$href.'" target="_blank" alt="example.com Sponsor!" title="example.com Sponsor!"><img border="0" src="'.$src.'" /></a>';
vB_Template::preRegister('navbar', array('randombanner' => $randombanner));
I have an idea that this could be accomplished using JavaScript but don't know where to start. I'd rather not add a library such as jQuery to the site, as it doesn't already use it for anything.
I would suggest sending a list of other ads as JSON, and then using JS to swap it. You could do that with a setInterval
. This is a little bit trickier without jQuery, do you have any other libraries on the site?
For the PHP, add
$ads_json=json_encode($banners);
underneath where you declare the $banners array.
Change your banner element to have an ID so we can access it via JS easily.
$randombanner = '<a id="sponsor_banner" href="'.$href.'" target="_blank" alt="example.com Sponsor!" title="example.com Sponsor!"><img border="0" src="'.$src.'" /></a>';
Then add to the $randombanner html...
<script>
var ads='.$ads_json.';
function swap_ad(){
var ad_el=document.getElementById("sponsor_banner");
var img=ad_el.getElementsByTagName('img')[0];
var random_ad=ads[Math.floor(Math.random()*items.length)];
ad_el.href=random_ad["href"];
img.src='.$path.'random_ad["src"];
};
window.setInterval(swap_ad,90000000);
</script>
It would be nice to put the script in the head. Putting it by the element will work though, not sure about the limitations of vBulletin.