I am writing a short script that connects to the LastFM api to get my last scrobbled song. The issue I am having is that the JSON version has an attribute for "now playing" which when you are currently listening to a song has the value of "true". However if there is no song playing the attribute doesn't exist at all.
This is the script I currently have and when I am listening to a song via spotify or iTunes etc... it works fine.
<p>
<p class="nowplaying"> <span class="track"></span> by <span class="artist"></span></p>
<p>
<script type="text/javascript">
$.getJSON('https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=JamesTaylor87&api_key=ADD-API-KEY-HERE&format=json', function(data) {
var artist = $(".artist"),
track = $(".track"),
np = $(".nowplaying"),
artistVal = data.recenttracks.track[0].artist["#text"],
trackVal = data.recenttracks.track[0].name,
nowplaying = data.recenttracks.track[0]["@attr"].nowplaying;
if(typeof nowplaying === "undefined"){
np.prepend("The last song I listened to was")
artist.append(artistVal);
track.append(trackVal);
} else {
np.prepend("I am currently listening to")
artist.append(artistVal);
track.append(trackVal);
}
});
</script>
However when I am not listening to anything I get the following error message (in safari) and nothing works:
undefined is not an object (evaluating 'data.recenttracks.track[0]["@attr"].nowplaying')
in chrome the error is displayed as follows:
Uncaught TypeError: Cannot read property 'nowplaying' of undefined
I have attempted to use an if statement for when it's undefined which hasn't worked and don't really know what else to try. Any help would be much appreciated.