Random background body images in SharePoint

Just had an interesting question…How do you get random background images on your SharePoint site. We needed it for a demo site and proved vaguely interesting.

The problem is that SharePoint sets the CSS class for the body after the page has loaded in the method AllowCSSFiltersOnIE8. This is the method which sets the ms-backgroundImage class on the body tag. This method is called when the body is loaded by using the _spBodyOnLoadFunctionNames() method.

So, this is a quick example of how to randomly change the background image. You’ll probably want to tidy it up for production (checking that certain scripts are loaded, moving the CSS into a file, etc), but it worked for our demo.

First you’ll need to modify the master HTML page and add the following to the <head> section…

<!--MS:<style type="text/css">-->
<!--
    .backOne{background-image:url('/images/img1.png')}
    .backTwo{background-image:url('/images/img2.png')}
    .backThree{background-image:url('/images/img3.png')}
-->
<!--ME: </style>—>

Thanks to Eric Overfield at PixelMill for the way to add a style to your HTML master page.

Then add a bit of script to the end of the page, just before the </body> tag…

<script>
  _spBodyOnLoadFunctionNames.push("swapBodyImage");
  function swapBodyImage(){
  var r = Math.random() * 3;
  var img = "backOne";
  if (r > 2) img = "backTwo";
  else if (r > 1) img = "backThree";
  CSSUtil.AddClass(document.body, img);}
</script>

The script will then randomly choose one of your styles and so set the background.
blog comments powered by Disqus

SharePoint on Windows Phone

AgilisPoint a free App for your Windows Phone