CODE

Show a random thing every page load

This could be used for showing a different hero image on a home page every time a person visits the page, or just to change things up a bit and give a bit of interest to a page.

v1.0.0

Ok, let’s just kick things off with saying this isn’t actually random, and it’s not triggered by page load. But for most users the effect will be that they see a different thing most times they load the page.

  1. In the example below we have three things that we want to show “randomly”.

    {% comment %}<!-- Treehouse CODE v1.0.0 -->{% endcomment %}
    {% assign msTime = "now" | date: "%L" | plus: 0 %}
    {% if  msTime > 666 %}
        Show 1
    {% elsif  msTime > 333 %}
        Show 2
    {% elsif  msTime > 0 %}
       Show 3
    {% endif %}
  2. If we had four things the code snippet would look like this:

    {% comment %}<!-- Treehouse CODE v1.0.0 -->{% endcomment %}
    {% assign msTime = "now" | date: "%L" | plus: 0 %}
    {% if  msTime > 750 %}
        Show 1
    {% elsif  msTime > 500 %}
        Show 2
    {% elsif  msTime > 250 %}
       Show 3
    {% elsif  msTime > 0 %}
       Show 4
    {% endif %}

    Explanation: We’re getting the milliseconds of the current time. If we have three things then we divide 1000 milliseconds by 3, and we show each thing 1/3 of the time, if we have 4 things then we divide 1000 millisecond by 4, and so on.

Comments or questions? Head over to the Treepl CMS forum to discuss with the community.