Question

I want to have multiple span.play without IDs which can be clicked and play some audio file.

Problem: Display the duration on only the current file $(this)

$('.play').each(function() {

    $(this).append('<span class="playIcon"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Fairytale_player_play.png/14px-Fairytale_player_play.png"></span><span class="playDur"></span>');


    $(this).click(function() {
        var file = this.firstChild;
        if (file.paused != false) {
            //+ stop all others before playing new one
            file.play();
        } else {
            file.pause();
        }
        file.addEventListener("timeupdate", function() {
            var len = file.duration,
                ct = file.currentTime,
                s = parseInt(ct % 60),
                m = parseInt((ct / 60) % 60);
            if (s < 10) {
                s = '0' + s;
            }
            $(".playDur").html('&nbsp;(' + m + ':' + s + ')');
            if (ct == len) {
                $(".playDur").html('');
            }
        }, false);
    });

});

Test:

http://jsfiddle.net/sQPPP/

http://jsfiddle.net/sQPPP/1/ - using $(this).children( ".foo" )

Was it helpful?

Solution

You need to save .play jQuery object in a variable, as this changes within the addEventListener callback.

http://jsfiddle.net/sQPPP/2/

$('.play').each(function(index) {
    var $play = $(this);
    $play.append('<span class="playIcon"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/7/76/Fairytale_player_play.png/14px-Fairytale_player_play.png"></span><span class="playDur"></span>');


    $play.click(function() {
        var file = this.firstChild;
        if (file.paused != false) {
            //+ stop all others before playing new one
            file.play();
        } else {
            file.pause();
        }
        file.addEventListener("timeupdate", function() {
            var len = file.duration,
                ct = file.currentTime,
                s = parseInt(ct % 60),
                m = parseInt((ct / 60) % 60);
            if (s < 10) {
                s = '0' + s;
            }
            $play.children( ".playDur" ).html('&nbsp;(' + m + ':' + s + ')');
            if (ct == len) {
                 $play.children( ".playDur" ).html('');
            }
        }, false);
    });

});​
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top