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">
jq(document).ready(function(){
  var dest=new Array();
  dest[0]='https://titanweb5.uwosh.edu/titanweb_prd/signon.html';
  dest[1]='https://titanweb3.uwosh.edu/titanweb_prd/signon.html';
  var rn=Math.floor(Math.random()*dest.length);
  jq("a[href$='https://titanweb5.uwosh.edu/titanweb_prd/signon.html']").attr("href", dest[rn]);
});
</script>

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.

 

Navigation