Jan de Vries
Jan de Vries

Reputation: 71

toggle button, but toggle only once

I have a nice code for a audio play-button. After clicking it becomes a pause-button. That's fine, but I want to keep it a pause button. So it should toggle only once. Would be nice to add some code, and not replacing by completely new code. The code:

<script>
function a(el){
play()
}

function b(el){
pause()
}

$(".btn-play").click(function() {
  var el = this;
  return (el.t = !el.t) ? a(el) : b(el);
 }); 
</script> 

Upvotes: 0

Views: 666

Answers (3)

AgataB
AgataB

Reputation: 647

This is a rather general answer for "I want to use the button only once", as there isn't much detail given in the question.

You can disable the button with $('.btn-play').attr("disabled", true) or $(".btn-play").unbind("click") - just make sure this picks only the button you want.

If you want the button to then have different functionality (pause instead of play or something) I would suggest defining handlers separately, so you can use .unbind("click", handler1) followed by .bind("click", handler2) or in some other way keep the two handlers separate, as per documentation here.

Upvotes: 0

fdomn-m
fdomn-m

Reputation: 28621

Assuming el.t == false means b(), simply add a pre-check:

$(".btn-play").click(function() {
  var el = this;
  if (!el.t) b(el);
  return (el.t = !el.t) ? a(el) : b(el);
}); 

if you mean it to be the other, then use if (el.t) b(el);

Personally, I'd simplify the code:

$(".btn-play").click(function() {
  var el = this;
  if (!el.t) b(el);
  el.t = false;
  a(el);
}); 

Upvotes: 1

GitProphet
GitProphet

Reputation: 1038

How about this: https://jsfiddle.net/e0evwnvu/

$(document).ready(function() {
  var isPauseButton = false;
  $('#btn').click(function() {
    if (!isPauseButton) {
        play();
      isPauseButton = true;
    } else {
        pause();
    }
  });
});

function play() {
    alert('play');
}

function pause() {
    alert('pause');
}

Upvotes: 0

Related Questions