Random Image/Text Rotator in CMS Block

Here’s a simple way to add a random image/text rotator in a CMS block – no php or template required – pure javascript!

I was looking for a way to add random (or specific) information to our customers as they browse the site. I needed (1) specific system message for things like order delays, system issues etc. When that wasn’t needed, I wanted to cycle through multiple messages – ie promo messages, images, links etc – any amount.

First thing you need to have is a place to display your cms block (I placed mine below the nav menu but you can have it wherever you’d like and any size. To display the cms block, just make sure you have the following code:

<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('YOUR_BLOCK_ID')->toHtml() ?>

Create a new CMS block and add the following:

<script language="JavaScript">

// if you want a system message to over-ride the random info, add the message (or image etc) between the single quotes

var system_message = ''

function random_message(){
var message=new Array()

// Change the array to whatever you want displayed in a random sequence - images, text etc ... change the array number for each, starting with one
message[1]='<div class="container"><h5 class = "notice-msg"><a href="{{store direct_url="xxx"}}">Special Deal: xxx - Shipping Included!</a></h5></div>'
message[2]='<div class="container"><h5 class = "success-msg"><a href="{{store direct_url="yyy"}}">Special Deal: yyyy</a></h5></div>'
message[3]='<div class="container"><h5 class = "error-msg"><a href="{{store direct_url="zzz"}}">zzzzzzz</a></h5></div>'

var ry = Math.floor(Math.random() * message.length)
if (ry == 0) { ry = 1 }

if (message[ry] != "") { document.write('<center>'+message[ry]+'</center>') }


if (system_message == "") { random_message()
} else {
if (system_message != "") { document.write('<center>'+system_message+'</center>') }


The array content can be anything you want displayed – plain text, images, system variables etc – you’re only limited by your creativity! Add or removed elements as needed. Any valid HTML is acceptable. Inline/CSS styles can also be added.

If you have a specific information (or image etc) you want to over-ride the array, simply put something in the system_message variable. As long as the system_message contains something, it will ignore the random_message(s). If both are empty, it’ll do nothing.

My example prints the info between <center> tags – you can change or remove as desired.

In the image below, a random promotional message (with link) is displayed below the Nav Bar


Leave a Reply