Sébastien Gicquel
Sébastien Gicquel

Reputation: 4386

How to add or remove audio attribute of html5 <audio>?

I've created a multi track player whith html5 and javascript.

var track_1 = document.getElementById('audio_1');

I've made custom control buttons : volume, play, stop, pause, for example :

$bt_play_audio_mixette_1.click(function() {
    if (track_1.paused == false) {
        track_1.pause();
    } else {
        track_1.play();
    }
});

I have a button "loop" and i want to modify to <audio> attribute loop dynamically.

I've tried with .attr(); or .prop(); but without success.

do you know what is wrong in this code :

var loop_1_active = true;
$bt_loop_audio_1.click(function() {
    if (track_1.prop("autoplay", true)) {
        track_1.prop("autoplay", false);
        loop_1_active = false;
    } else {
        track_1.prop('loop', true)
        track_1.attr("autoplay", true);
    }
});

EDIT :

If i use a jquery object :

var track_1_B = $('#audio_1');

i can't use pause();

error :ReferenceError: track_1 is not defined track_1.pause();

If i use pure JS :

var track_1 = document.getElementById('audio_1'); 

i can use pause(); but i can't change the loop attribute

Upvotes: 1

Views: 3706

Answers (2)

Peter
Peter

Reputation: 16943

use jquery too:

var $track_1 = $('#audio_1'); // jquery object
var track_1 = document.getElementById('audio_1'); // pure js DOM element

And use jquery methods on jquery object only.

$track1.click(//...
$track1.attr(//...
$track1.prop(//...

Other methods on DOM element

trakck1.pause();

Upvotes: 3

Musa
Musa

Reputation: 97707

if (track_1.prop("autoplay", true)) { actually sets the autoplay property to true rather than checking if it is true and will always return a truthy value. Use instead if (track_1.prop("autoplay")) {. I now see that track_1 is a dom element and not a jQuery object so it needs to be transformed into one to use prop()... e.g. $(track_1).prop("autoplay"). Also you can access the element properties directly no need to use jQuery

var track_1 = document.getElementById('audio_1');
var loop_1_active = true;
$bt_loop_audio_1.click(function() {
    if (track_1.autoplay) {
        track_1.autoplay = false;
        loop_1_active = false;
    } else {
        track_1.loop = true;
        track_1.autoplay = true;
    }
});

Upvotes: 2

Related Questions