Search code examples
jqueryhtmlaudiohtml5-audiotree-traversal

.next() .prev() Traverse Through Multiple <article> elements


I'm working on a simple HTML5 audio playlist (audio.js) that changes to the next song in a Wordpress <article ul li> post. So I'm having a bit of trouble traversing through multiple <article> tags and retrieving the <ul li> of each on .next() and .prev(). I'm starting to think using these selectors is not the best solution.

<script>
  $(function() { 
    // Setup the player to autoplay the next track
    var a = audiojs.createAll({
      trackEnded: function() {
        var next = $('article ul li').next();
        var title = $('img', this).attr("title");
            $("a.songtitle").text(title);
        if (!next.length) next = $('article ul li').first();
        audio.load($('a', next).attr('data-src'));
        audio.play();
      }
    });

    // Load in the first track
    var audio = a[0];
        first = $('article ul a').attr('data-src');
    $('article ul li').first();
    audio.load(first);

    // Load in a track on click
    $('article ul li').click(function(e) {
      e.preventDefault();
      var title = $('img', this).attr("title");
        $("a.songtitle").text(title);
      audio.load($('a', this).attr('data-src'));
      audio.play();
    });
    // Keyboard shortcuts
    $(document).keydown(function(e) {
      var unicode = e.charCode ? e.charCode : e.keyCode;
         // right arrow
      if (unicode == 39) {
        var next = $('article ul li').next();
        if (!next.length) next = $('ul li').first();
        next.click();
        // back arrow
      } else if (unicode == 37) {
        var title = $('img', this).attr("title");
            $("a.songtitle").text(title);
        var prev = $('article ul li').prev();
        if (!prev.length) prev = $('article ul li').last();
        prev.click();
        // spacebar
      } else if (unicode == 32) {
        audio.playPause();
      }
    })
  });
</script>

How can I alter to this code to switch between multiple <article ul li> tags to skip to the next/prev song? Any help would be greatly appreciated! Thank you!

Edit: Here's what I'm trying to do. But as you can see it's not skipping songs to each <article ul li> tag. Audio.js automatically finds all <a> tags and gets the data-src attribute to load up a song. http://jsfiddle.net/UkrZx/


Solution

  • Don't know why it wouldn't recognize next/prev <article> elements but I changed the original Wordpress post content to output the posts between just the <li> elements instead. Strange but at least it works now.

    My code is now like this: http://jsfiddle.net/HxVaj/2/.