I had been using a JavaScript solution from javascriptkit.com to randomly show one option from a series on a page. All the options are wrapped in DIVs and placed in a single include file. This first solution used JS to set a CSS display:none; to all but one of a series of DIVs in a document. Nice as it was, the resulting xHTML markup would not validate properly. [UPDATE – this is due to the fact that xHTML needing extra CDATA markup around any JavaScript contained within.] Another minus was that, although sold as plus for web-crawlers etc (all options remain in the HTML at all times), if JavaScript was off then all of the options would appear and muck-up the carefully honed design.

I looked for fixes to the validation issues caused by this line for (var i=0; i<alldivs .length; i++) but to no avail. Half a day of searching later and after trying these other options I found the answer;

The Answer

None of these worked for me. The best (only) solution I found before the sun went down was from Joe Crawford. Based on PHP’s srand function
this solution allowed me to wrap PHP around the include file with the options and bingo; it works. As this is server side now – only one DIV will be in the HTML so no problem if JavaScript is off.

Happy.

Last updated on 5th September 2018