Anyone know of some code to rotate HTML banners?

Discussion in 'Web Design and Development' started by yasyugixyugi, May 21, 2013.

  1. yasyugixyugi macrumors newbie

    Apr 25, 2013
    Hi everyone,

    I've got a few HTML banners that I'd like to rotate on a website. Does anyone know of any code, such as Javascript or something, that will let me randomly rotate these HTML banners? So when you refresh the webpage, the banner will change?

  2. enigma2118 macrumors regular

    Jan 7, 2006
  3. elppa, May 25, 2013
    Last edited: May 25, 2013

    elppa macrumors 68040


    Nov 26, 2003
    It's just a case of sticking the images in a list and picking one at random.

    <!doctype html>
    		var banners = [];
    		banners.push({src: "image1.png", alt: "Image 1"});
    		banners.push({src: "image2.png", alt: "Image 2"});
    		banners.push({src: "image3.png", alt: "Image 3"});
    		banners.push({src: "image4.png", alt: "Image 4"});
    		banners.push({src: "image5.png", alt: "Image 5"});
    		window.onload = function() {
    			var index = Math.floor(Math.random() * banners.length);
    			var ad = document.getElementById("ad");
    			ad.setAttribute("src", banners[index].src);
    			ad.setAttribute("alt", banners[index].alt); = "block";
    		#ad {
    			display: none;
    			#ad {
    				display: block;
    	<img id="ad" src="image1.png" alt="Image 1" />
  4. yasyugixyugi thread starter macrumors newbie

    Apr 25, 2013
    Thank you very much for that - However the banners are not images, they are HTML banners... So would it be possible to do this same setup, but rotate bits of HTML code rather than images?

    Thank you!
  5. SrWebDeveloper, May 30, 2013
    Last edited: May 30, 2013

    SrWebDeveloper macrumors 68000


    Dec 7, 2007
    Alexandria, VA, USA
    Try this:

    "PHP Random Text Banner Rotator script provides you the simplest way to add banner ads to your website without the need for a database. PHP RandomRotator will also randomise anything you want including: - Plain text, Images, Banners, Quotes, and Links etc. You can place any number of banners, any size, anywhere on your website by using one simple line of code. " (from that site)

    On a side note, I would likely add session cookie support to store the ID of the current banner and add a condition so the new randomly generated ID does not match the cookie value to avoid the same banner showing up twice in a row on page refreshes for the end user. Sure, session ID could be used but session cookies alone are traditionally used for simple stuff like this. FYI
  6. yasyugixyugi thread starter macrumors newbie

    Apr 25, 2013
    Thank you very much!

Share This Page