You are here: Home / Documentation / How To's / JavaScript to randomly set a link

JavaScript to randomly set a link

by nguyen — published Dec 21, 2011 03:30 PM, last modified Aug 16, 2016 10:50 AM
in a portlet

We have a static text portlet on this page that contains a link to a specific URL.  We wanted to have that link randomly change to point to one of two URLs.  Here is the script I added to the body of the static text portlet.  Remember: the safe HTML portal transform does not get applied to portlets, so this works for portlets but will not work in the main body of the page unless you mess with your site's filtering settings (mentioned elsewhere on this site).

<script type="text/javascript">
  var dest=new Array();
  var rn=Math.floor(Math.random()*dest.length);
  jq("a[href$='']").attr("href", dest[rn]);

Information on randomly generating messages 

Information on changing href attributes

This is a good page to try out jQuery code live.  Remember, though, that Plone sites expect you to use jq instead of $ to invoke jQuery.