Richard Bland
Richard Bland

Reputation: 73

Dynamically change the src of a script tag

I've read some of the similar questions but they don't quite answer this query of mine.

I am building a website that uses Viddler video hosting. In their embed code you recieve a script tag, like this:

<script src="http://www.viddler.com/tools/vidget.js?widget_type=js_list&amp;widget_width=940&amp;source=playlist&amp;user=USERNAME&amp;playlist=XXXXXXXXXXXXXXXX&amp;style=grid&amp;show_player=true&amp;player_type=simple&amp;max=12&amp;videos_per_row=6&amp;v=2.0&amp;id=XXXXXXXXXX" type="text/javascript" charset="utf-8"></script>

I have x'd out my client's ID, but the bit I am interested in changing dynamically is the playlist.

Viddler suggested just using a tabbed container to house all of the video playlists, but I am not so comfortable with having that amount of coding on the page if I don't need it.

My workaround is to somehow use buttons to change the script source or just the playlist= variable.

Does anyone have any ideas on how this could be achieved?

Upvotes: 2

Views: 4551

Answers (1)

user920041
user920041

Reputation:

With jQuery you can load and execute JavaScript on demand. Before loading the script, append the playlist part to the script url like this:

HTML

<a href="playlisturl" class="playlist-link">Play list A</a>
<a href="playlisturl" class="playlist-link">Play list B</a>
<a href="playlisturl" class="playlist-link">Play list C</a>

jQuery

$(".playlist-link").click(function(e){
    e.preventDefault();
    var playlist = $(this).attr("href");

    var url = 'http://www.viddler.com/tools/vidget.js' +
                  '?widget_type=js_list' +
                  '&widget_width=940' +
                  '&source=playlist' +
                  '&user=USERNAME ' +
                  '&playlist='+ playlist +
                  '&style=grid'+
                  '&show_player=true'+
                  '&player_type=simple'+
                  '&max=12'+
                  '&videos_per_row=6'+
                  '&v=2.0'+
                  '&id=XXXXXXXXXX';

    $.getScript(url, function(data, textStatus){
        alert('This is executed after your script is loaded');
    });
});

Upvotes: 1

Related Questions