Reputation: 145
I have a small script that loads in the last song I listened to from last.fm with jQuery, as seen below:
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=paul_r_schaefer&api_key=0f680404e39c821cac34008cc4d803db&format=json', function(data) {
var song = $(".song"), artistVal = data.recenttracks.track[0].artist["#text"], trackVal = data.recenttracks.track[0].name;
song.append(artistVal + " \u2014 " + trackVal); });
Is there any way I can make it remove what it already appended to the <span class="song"></span>
and load again? For the life of me, I can't figure out a way that doesn't duplicate the song.
EDIT: This works, however, it has a delay when it first loads. Is there a way I can get it to run once, then refresh every 3 seconds?
function listens() {
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=paul_r_schaefer&api_key=0f680404e39c821cac34008cc4d803db&format=json', function(data) {
var song = $(".song"), artistVal = data.recenttracks.track[0].artist["#text"], trackVal = data.recenttracks.track[0].name;
song.html(artistVal + " \u2014 " + trackVal);
});
}
setInterval(listens, 3000);
EDIT 2: This gets rid of the lag, just is there a way I can slim this down?
listens();
function listens() {
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=paul_r_schaefer&api_key=0f680404e39c821cac34008cc4d803db&format=json', function(data) {
var song = $(".song"), artistVal = data.recenttracks.track[0].artist["#text"], trackVal = data.recenttracks.track[0].name;
song.html(artistVal + " \u2014 " + trackVal);
});
}
setInterval(listens, 3000);
Upvotes: 0
Views: 113
Reputation: 145
This works good enough for me.
listens();
function listens() {
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=paul_r_schaefer&api_key=0f680404e39c821cac34008cc4d803db&format=json', function(data) {
var song = $(".song"), artistVal = data.recenttracks.track[0].artist["#text"], trackVal = data.recenttracks.track[0].name;
song.html(artistVal + " \u2014 " + trackVal);
});
}
setInterval(listens, 2000);
Upvotes: 0
Reputation: 23283
Your problem here is that jQuery's .append()
well, appends. It appends, or adds, onto what is the existing HTML in the element. You want to replace the element's HTML entirely, so your approach should be something like this:
$.getJSON('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=paul_r_schaefer&api_key=0f680404e39c821cac34008cc4d803db&format=json', function(data) {
var song = $(".song"), artistVal = data.recenttracks.track[0].artist["#text"], trackVal = data.recenttracks.track[0].name;
song.html(artistVal + " \u2014 " + trackVal); });
Check out $.html(htmlString):
From the jQuery API:
Set the HTML contents of each element in the set of matched elements.
Upvotes: 2