JSFiddle - React, Tailwind, and code Playground
by Chris Hughes
HTML
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.1/handlebars.min.js"></script>
<link rel="stylesheet" href="https://d2c87l0yth4zbw.cloudfront.net/reboot.css">
<div class="container">
<h2>Discography</h2>
<p>Click an album cover to hear a 30 second preview, or click the button to play the album on Spotify!</p><br />
<div id="results"></div>
</div>
<script id="results-template" type="text/x-handlebars-template">
{{#each albums.items}}
<div style="background-image:url({{images.0.url}})" data-album-id="{{id}}" class="cover"><a href="{{external_urls.spotify}}"><div class="spotify-button"><img src="https://developer.spotify.com/wp-content/uploads/2014/06/play_on_spotify-green.png" /></div></a></div>
{{/each}}
</script>
CSS
body {
padding: 20px;
}
.cover {
width: 300px;
height: 300px;
display: inline-block;
background-size: cover;
position: relative;
border: 2px solid #fff;
}
.cover:hover {
cursor: pointer;
}
.cover.playing {
border: 2px solid #e45343;
}
.spotify-button {
position: absolute;
bottom: 0;
right: 5px;
cursor: pointer;
}
JavaScript
// find template and compile it
var templateSource = document.getElementById('results-template').innerHTML,
template = Handlebars.compile(templateSource),
resultsPlaceholder = document.getElementById('results'),
playingCssClass = 'playing',
audioObject = null;
var fetchTracks = function (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/albums/' + albumId,
success: function (response) {
callback(response);
}
});
};
var searchAlbums = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: 'artist:' + query,
type: 'album',
market: "US"
},
success: function (response) {
resultsPlaceholder.innerHTML = template(response);
}
});
};
results.addEventListener('click', function(e) {
var target = e.target;
if (target !== null && target.classList.contains('cover')) {
if (target.classList.contains(playingCssClass)) {
audioObject.pause();
} else {
if (audioObject) {
audioObject.pause();
}
fetchTracks(target.getAttribute('data-album-id'), function(data) {
audioObject = new Audio(data.tracks.items[0].preview_url);
audioObject.play();
target.classList.add(playingCssClass);
audioObject.addEventListener('ended', function() {
target.classList.remove(playingCssClass);
});
audioObject.addEventListener('pause', function() {
target.classList.remove(playingCssClass);
});
});
}
}
});
searchAlbums('Leonard Cohen');