with jquery how to execute a function when clicking and when clicking again execute another function?

2

I have not used much jquery and I can not do this:

I have a li with id="play1" when I click on it: play a song and when I come back click on "play1" to pause the playback. so always, play / stop.

<li id="play1">



$( "#play1" ).click(function() 
{
    //si play1 click ejecutar audio1.play();
    //otro click en play1 ejecutar audio1.pause();
});

use a counter?

    
asked by Rafael Hernández 07.10.2016 в 14:17
source

2 answers

2

Put a flag that indicates the status of the player. You can create the flag with JavaScript:

var playing = false;

$('#1').click(function() {
  if(!playing) {
    audio1.play();
    playing = true;
  } else {
    audio1.pause();
    playing = false;
});

Or via a data- attribute:

<div id="audio1" data-status="paused">...</div>

And you get the attribute in the click event:

$('#audio1').click(function() {
  var status = $(this).attr('data-status');
  if(status === "paused") {
    audio1.play();
    $(this).attr('data-status', 'playing');
  } else {
    audio1.pause();
    $(this).attr('data-status', 'paused');
  }
});
    
answered by 07.10.2016 / 14:48
source
1

DEMO in JS BIN

I leave here an elegant example to be able to add more rows of audios without repeating again and again the same code in jQuery.

$(document).on('click', '.playAudio', function(){
 
  var whichAudio = $('#audio' + $(this).data('audio'));
  
  whichAudio[0].paused
  ? whichAudio[0].play() 
  : whichAudio[0].pause();    
});
li {
  list-style: none;  
}

li:nth-child(odd) {
  cursor: pointer;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<ul>
  <li class="playAudio" data-audio="1">Play audio #1</li>
  <li>-------------</li>
  <li class="playAudio" data-audio="2">Play audio #2</li>
  <li>-------------</li>
  <li class="playAudio" data-audio="3">Play audio #3</li>
</ul>

<audio id="audio1">
  <source src="http://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3">
</audio>
<audio id="audio2">
  <source src="http://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3">
</audio>
<audio id="audio3">
  <source src="http://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3">
</audio>
    
answered by 07.10.2016 в 16:10