Question

I'm a javascript beginner and I'm getting this error when I'm trying to use the soundcloud API :

 ReferenceError: $ is not defined
 $("#stream").live("click", function(){

I removed client_ID and track_ID but here is my script :

 <script type="text/javascript" src="http://connect.soundcloud.com/sdk.js"></script>
<script type="text/javascript">

    SC.initialize({
        client_id: "000000000000000000"
    });  

    $("#stream").live("click", function(){
        SC.stream("/tracks/000000000", {autoPlay: true});
    });

 </script>

And the HTML :

 <head> 
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/player.css" />
</head>

<body>
    <div id="container">
        <h1>earth. home. destroyed.</h1>
            <nav>
                <ul>
                    <li id="stream">► saturn boy</li>
                    <li>► gold</li>
                    <li>► earth</li>
                    <li>► from the sun</li>
                    <li>► cosmic landscapes</li>
                </ul>
            </nav>
    </div>

 </body>

Any help at all would be greatly appreciated :)

Thank you !!

Was it helpful?

Solution

From the example of the scripts, it looks like you're missing a reference to jQuery (which isn't a default library - you have to explicitly include it before any scripts that use it on pages where you need it).

Adding this (before your other script tags) should fix it:

<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>

Also, I would recommend not using 'live', as it's deprecated. Instead, you should use 'on', together with delegation. With your HTML example above, this could be done with the following edit:

$('#container > h1 > nav > ul').on('click', '#stream', function(){
    SC.stream("/tracks/000000000", {autoPlay: true});
});
  • This will trigger the handler only if the click was on the #stream element - but the #stream element doesn't need to be on the page to begin with - only the container ul does. If you're creating the ul dynamically as well, you can go 'up' one level and change the selector to this #container > h1 > nav (which has a similar effect, but here the ul can be dynamically added as well).

More on event delegation with 'on': https://api.jquery.com/on/

..hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top