Tuesday, November 24, 2009

'What I was listening to' box in my posts

I recently implemented a 'system' in where I show one or more songs I was listening to whilst writing a blog post, in this form:



To do that, I wrote a small script:

var blogmusic = function () {
    var lastContainerDone = 0;
    return function (music) {
        var musiccount = music.length,
            blogmusic = $(".blogmusic").eq(lastContainerDone++),
            header = $("<div/>").addClass("header");
        header.append("<center>What I was listening to</center>");
        var musiclist = $("<div/>").addClass("musiclist");
        for (var i = 0; i & lt; musiccount; i += 1) {
            var song = music[i];
            var listing = $("<div/>").addClass("listing");
            var songname = $("<span/>").addClass("songname").html('<a href="' + (song.link || '#') + '" target="_blank">"' + song.name + '"</a>');
            var artist = $("<span/>").addClass("artist").html('- ' + song.artist);
            listing.append(songname);
            listing.append(artist);
            musiclist.append(listing);
        }
        blogmusic.html(header);
        blogmusic.append(musiclist);
    };
} ();

And I invoke the script in my blog posts like such:

<div class="blogmusic">
<script>
blogmusic([
{ 
    artist : 'Jerry Lee Lewis',
    name : 'Whole Lotta Shakin\'',
    link : 'http://listen.grooveshark.com/#/song/Whole_Lotta_Shakin/6325468'
}
]);
</script>
</div>