Home > Software engineering >  onclick button to choose whether to loop audio or not
onclick button to choose whether to loop audio or not

Time:09-09

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.

CodePudding user response:

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

CodePudding user response:

id say similar to this JavaScript: Set attribute to video element because essentialy what you are doing is on click adding the autoplay attribute (likely if a check box is checked) .

CodePudding user response:

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