Tonechas
Tonechas

Reputation: 13743

How to periodically change the content of an HTML block in a Moodle course?

I need to display multiple pictures one by one at different time periods in a Moodle course. To that end I'm using an HTML block with one picture at a time (in my first attempt I used a random glossary entry block, which turned out to be an inadequate solution). The HTML block approach is a bit cumbersome as whenever I want to display a different picture I have to manually update the HTML block.
I'd like to have the pictures in the HTML block changed automatically on a daily or weekly basis. Can this even be done? If so, would someone please put me on the right track?

Upvotes: 0

Views: 360

Answers (1)

DerKanzler
DerKanzler

Reputation: 53

I think the key to this question is that you can add javascript to the html block. Thats also why these capabilities are marked with an XSS warning. This is my approach:

  1. Add a HTML Block to your Moodle course
  2. Add all the pictures you want in the order they should appear on a weekly basis.
  3. Depending which editor you are using (most probably atto) find the "html" button the edit the raw text (Help: MoodleDocs) and click it.
  4. Now you can see the <img> tags of the pictures you previously added. Add the following javascript to rotate through these pictures on a weekly basis:
<script>
    // Get the week number.
    Date.prototype.getWeek = function() {
        var onejan = new Date(this.getFullYear(), 0, 1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
    }
    var numberofweek = (new Date()).getWeek();

    var parent = document.currentScript.parentNode;
    var pictures = parent.querySelectorAll('img');
    for (var picturenumber = 0; picturenumber < pictures.length; picturenumber++) {
        if (!(numberofweek % pictures.length == picturenumber)) {
            // Hide all pictures that are not mapped to this week.
            pictures[picturenumber].style.display = 'none';
        }
    }
</script>

Cons of this approach:

  1. The pictures still get loaded. Some students may find out about this. So don't put any picture in there that should be accessible in the next week.
  2. Some students might get different pictures sometimes depending on the timezone of their local machine.

Pros of this approach:

  1. You can edit the pictures and the order pretty easy
  2. You dont have to install any plugin as block_html comes with moodle

Tested on Moodle 3.9.x
The pictures will start from the beginning if there are more weeks than available pictures.

Upvotes: 1

Related Questions