sigil
sigil

Reputation: 9546

"Cannot call method 'oEmbed' of null" when embedding Soundcloud player in dynamically generated Div

Using the Soundcloud JavaScript API, I want to dynamically generate a page of player widgets using track search results. My code is as follows:

<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>

<script>
function makeDivsFromTracks(tracks,SC)
{
 var track;
 var permUrl;
 var newDiv;
 for(var ctr=0;ctr<tracks.length;ctr++)
 {
  newDiv=document.createElement("div");
  newDiv.id="track"+ctr;
  track=tracks[ctr];
  SC.oEmbed(track.permalink_url,{color:"ff0066"},newDiv);
  document.body.appendChild(newDiv);
 }
}
</script>

</head>
<body>

<script>
SC.initialize({
    client_id: 'MY_CLIENT_ID'
});
SC.get('/tracks',{duration:{to:900000},tags:'hitech',downloadable:true},
        function(tracks,SC)
        {
         makeDivsFromTracks(tracks,SC);
        });
</script>

</body>
</html> 

When I load this, the SC.oEmbed() call throws an error:

Uncaught TypeError: Cannot call method 'oEmbed' of null 

which would seem to indicate that either the divs aren't being generated or the search results aren't being returned, but if I remove the SC.oEmbed() call and replace it with:

newDiv.innerHTML=track.permalink_url;

then I get a nice list of the URLs for my search results.

And if I create a widget using a static div and static URL, e.g.

<body>
<div id="putTheWidgetHere"></div>
<script>
SC.initialize({
    client_id: 'MY_CLIENT_ID'
});
SC.oEmbed("http://soundcloud.com/exampleTrack", {color: "ff0066"},  document.getElementById("putTheWidgetHere"));
</script>
</body>

then that works fine as well. So what's the problem with my oEmbed() call with these dynamically created elements?

Upvotes: 0

Views: 1034

Answers (1)

sigil
sigil

Reputation: 9546

Solved it. I took out the SC argument from the callback function and makeDivsFromTracks(), and now all the players show up. Not sure exactly why this works--maybe it has to do with the SC object being defined in the SDK script reference, so it's globally available and doesn't need to be passed into functions?

Anyways, working code is:

<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>

<script>
function makeDivsFromTracks(tracks)
{
 var track;
 var permUrl;
 var newDiv;
 for(var ctr=0;ctr<tracks.length;ctr++)
 {
  newDiv=document.createElement("div");
  newDiv.id="track"+ctr;
  track=tracks[ctr];
  //newDiv.innerHTML=track.permalink_url;
  SC.oEmbed(track.permalink_url,{color:"ff0066"},newDiv);
  document.body.appendChild(newDiv);

 }
}
</script>

</head>
<body>

<script>
SC.initialize({
    client_id: 'MY_CLIENT_ID'
});
SC.get('/tracks',{duration:{from:180000,to:900000},tags:'hitech',downloadable:true},function

(tracks){makeDivsFromTracks(tracks);});
</script>

</body>
</html>

Upvotes: 1

Related Questions