views:

58

answers:

1

I am trying to make an super easy audio player with jQuery.

How would you convert this

   <a href="song.mp3">Song</a>

to this?

   <object type="application/x-shockwave-flash" data="dewplayer.swf" >
        <param name="flashvars" value="mp3=blank.mp3" />
   </object>

   <a href="song.mp3">Download</a>

So what needs to happen as I understand it

  • The name of the link is changed to Download
  • the flash object code is pasted before the link,
  • the mp3 urls are stored,
  • each respective mp3 url are inserted into each corrolating value="mp3=____"

This utilizes a simple flash audio player, Dewplayer.

Any thoughts?

+1  A: 

Like this (untested):

// on document ready,
$(function ()
{
    var objTagOpen = '<object type="application/x-shockwave-flash"'
                     + ' data="dewplayer.swf">'
                     + '<param name="flashvars" value="mp3=',
        objTagClose = '" /> </object>';

    // find all the links whose href ends with '.mp3',
    // and for each one,
    $('a[href$=.mp3]').each(function ()
    {
        var $this = $(this);

        // insert the flash <object> with the flashvars parameter
        $this.before(objTagOpen + $this.attr('href') + objTagClose);

        // then rewrite the link itself
        $this.text('Download');
    });
});

super-easy indeed.


Edit: Pekka's absolutely right about using a rel to allow you to have normal mp3 links as well. In that case, all you need to do is rewrite your initial selector, from

$('a[href$=.mp3]')

to

$('a[href$=.mp3][rel=mp3]')
Matt Ball
Wow! Thank you so much. Sometimes jQuery can be so vast and intangible I have a hard time understanding it. Any recommendations for how to learn jQuery?
Nathaniel
I tried this code and it works perfectly. So let me make sure I know what is going on. I wasn't familiar with objTagOpen and Close. Thanks again.
Nathaniel
@amulek: pretty much the same way I go about learning anything. **Use it/do it/try it a lot.** Practice and repetition are central to learning. When you run into something you can't figure out, ask others (like SO!). As for the vastness that is jQuery: it's really not that bad, if you only look at the core (e.g. not jQuery UI or any of the plugins). Only worry about the bits and pieces of jQuery that you need to use in order to write a particular line of code or function. **Small bites.**
Matt Ball
@amulek: the `objTagOpen` and `objTagClose` are just strings that I broke out into their own variables to make the code cleaner and a bit less messy. I could have just as well done this instead: `$this.before('<object type="application/x-shockwave-flash" data="dewplayer.swf"><param name="flashvars" value="mp3=' + $this.attr('href') + '" /> </object>');` but you see how ugly that is :)
Matt Ball