Mastodon Photostream on Static Websites

Date: 2019-01-20

During the rebuilt of this website, I had the wish to show a dynamic Photostream of the pictures that I posted on my Mastodon account over at @chaos.social. After some fiddling around, I build a small Javascript snippet that uses JQuery to fetch my status updates from the public API and display them.

$(document).ready(function() {
    var self = this;
    $.ajax('https://mastodon.social/api/v1/accounts/267185/statuses?only_media=true&limit=40', {
        dataType:"json",
        success:function(data) {
        $(data).each(function () {
            var toot = this;
            $(this.media_attachments).each(function() {
                var url = this.preview_url;
                $('#enclosures').append(
                    $('<a>', {href: toot.uri})
                        .css('height', '260px')
                        .css('width', '260px')
                        .css('display', 'inline-block')
                        .css('background-image', 'url(' + url + ')')
                        .css('background-size', 'cover')
                        .css('background-repeat', 'no')
                        .css('background-position', '50% 50%')
                        .css('padding', '0')
                );
            });
        });
    }});
});

Somewhere on that page, you have to have an <div id='encolsures'></div> tag and your user must allow cross-site access to your Mastodon instance. If you want to use this snippet, you also have to replace my Mastodon user id (267185) with your id on your server. One kind of simple variant to find your id, is to grab the JSON from the public timeline (e.g. /api/v1/timelines/public) directly after you have posted some public test toot.