0

This is my html and js file:

window.onload = function(){
 SC.initialize({
  client_id: "f5311a935daa5ecf6440f92183e77df1"
 });
 
 var menuLinks = document.getElementsByClassName("genre");
 for (var i=0; i < menuLinks.length; i++){
  var menuLink = menuLinks[i];
  menuLink.onclick = function(e){
   e.preventDefault();
   playSounds(menuLink.innerHTML);
  };
 };
};

function playSounds(genre){
 SC.get('/tracks', {genres: genre}, function(tracks){
  var random = Math.floor(Math.random()*49);
  SC.oEmbed(tracks[random].uri, {autoplay: false}, document.getElementById("content"));
 });
};
<html>
<head>
 <title>SoundCloud API</title>
 <script type="text/javascript" src="script.js"></script>
 <script src="//connect.soundcloud.com/sdk-2.0.0.js"></script>
</head>

<body>
<ul>
<li><a href="#" class="genre">electronic</a></li>
<li><a href="#" class="genre">trap</a></li>
<li><a href="#" class="genre">dubstep</a></li>
</ul>

<div id="content"></div>
</body>
</html>

So basically when I click on any of the links, it should search for that particular genre but instead it searches only for dubstep no matter which link I click on. Can anyone please help?

1 Answers1

0

Replace

playSounds(menuLink.innerHTML);

with

playSounds(this.innerHTML);

The reason it did not work is that when you click on a link, it will look for menuLink, which now equals the last one defined in the loop (<a>dubstep</a>).

blex
  • 24,941
  • 5
  • 39
  • 72
  • the console also shows an error: Uncaught TypeError: Cannot read property 'uri' of undefined (anonymous function) @ script.js:19 (anonymous function) @ sdk-2.0.0.js:1 window.SC.SC.Helper.merge._xhrRequest.request.onreadystatechange @ sdk-2.0.0.js:1 – user1954689 Jul 17 '15 at 13:50
  • @user1954689 In your `playSounds` function, `tracks` is always an array with 10 items in it. So you should use `10` instead of `49` in `random`. – blex Jul 17 '15 at 13:57
  • Thanks a lot man! That helped a lot :) – user1954689 Jul 17 '15 at 14:30