onclick button to choose whether to loop audio or not

Viewed 34

I have a simple audio here that goes on loop.

<audio controls loop>
          <source src="audio.mp3">
        </audio>

I would like to know if it is possible to let the user choose whether to let this audio continue looping or not with a onclick button function.

3 Answers

You can set/unset the loop attribute with javascript document.getElementById('player_id').removeAttribute('loop')

You can try this

First create a button and then use this

document.querySelector('#btn-id').addEventListener('click', ()=>{
    var player = document.querySelector('#player_id');
    if (player.hasAttribute('loop')) { 
       player.removeAttribute('loop');
    } else {
       player.setAttribute('loop','loop');
    }
}

replace player_id with your audio player id and replace btn-id with your button id.

Related