Blog

A javascript 'Now Playing' widget for your own website (w/ Last.fm)

Music is the universal language. And what better way to personalise your own website with a widget that gives your reader some insight in your musical tastes. I thought the same.

Turns out is not that hard to do! If you're on desktop, you can see the song I am currently playing (if I am). Here's how I did it:

Last.fm for displaying your music tracks

  1. I signed up to Last.fm and connected my favourite music service (so it 'scrobbles' correctly). There, I got a Last.fm API account.
  2. After the sign-up, I copied the API key and saved the rest of the information, as the page tells me to.
  3. Added the following HTML to my static site. <div class="listeningTo"></div>
  4. Added the following javascript to my main Javascript file:
$(document).ready(function() {
  $.getJSON("http://ws.audioscrobbler.com/2.0/?method=user.getRecentTracks&user=USERNAMEGOESHERE&api_key=ENTERYOURAPIKEYHERE&limit=2&format=json&callback=?",
  // Make sure you put your OWN username and API key to this call
  function(data) {
      var html = '';
      var counter = 1;
      $.each(data.recenttracks.track, function(i, item) {
          if(counter == 1 && item['@attr'] !== undefined && item['@attr'].nowplaying) {
              html += '<span>Now Playing: </span><br><span><strong>' + item.name + '</strong><br> by ' + item.artist['#text'] + '</span>';
          }
          counter++
      });
      $('.listeningTo').append(html);
  });
});

This code does include a few particularities. I started with a loop to go through all recent tracks, but ended up only using the most recent track. I kept the loop for when I want to expand on the script in the future.

Second, I wanted the song to show only when I am actually playing it. So I checked whether the attribute 'nowplaying' exists in what I got from Last.fm. If it doesn't, the script doesn't add the song to its HTML placeholder.

Third, I did not want to take up precious data and screen estate on mobile devices. So I decided to wrap all of the code in a check for mobile devices. It's not a necessary function, after all.

This is what that looks like:

function isMobile() {
  return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent));
}

if (!isMobile()) {
// The previous Last.FM script goes here
};

Let me know in a webmention when you added your Now Playing widget to your own website! In the next note I will give you a small CSS snippet of that fake 'equaliser' you can see on my own widget.