Using one button to turn a feature on and off, not two buttons

I currently use two buttons (Go, Stop) to call and turn on / off my function. But is it possible to use one button to call a function to disable or enable. For example, pressing a button will make it blue, this will enable the function, pressing the button again will make it white, this will disable the button.

My current code:

<button id="go">Go</button>
<button id="stop">STOP!</button>
<div class="block"></div>
   <style>
  #draggable {
   width: 150px;
    height: 150px;
     padding: 0.5em;
     top:5%;
     left: 5%; }
  </style>
<script>
// Start animation
$( "#go" ).click(function() {
  $( ".block" ).draggable();
});
// Stop animation when button is clicked
$( "#stop" ).click(function() {
$( ".block" ).draggable( "disable" );
});
$( "#go" ).click(function() {
$( ".block" ).draggable( "enable" );
});

</script>
<button id="go">Go</button>
<button id="stop">STOP!</button>
<div class="block"></div>
   <style>
  #draggable {
   width: 150px;
    height: 150px;
     padding: 0.5em;
     top:5%;
     left: 5%; }
  </style>
<script>
// Start animation
$( "#go" ).click(function() {
  $( ".block" ).draggable();
});
// Stop animation when button is clicked
$( "#stop" ).click(function() {
$( ".block" ).draggable( "disable" );
});
$( "#go" ).click(function() {
$( ".block" ).draggable( "enable" );
});

</script>
      

Run codeHide result


+3


source to share


2 answers


Of course, all you need to do is keep track of the state, for example a flag

$("#go").on('click', function () {

    var flag = $(this).data('draggable');

    $(".block").draggable( flag ? 'disable' : 'enable' );

    $(this).data('draggable', !flag);
});

      



FIDDLE

+2


source


Can try jquery in your click function



$(this).toggleclass("stop")
*insert code to test if class is stop"

      

0


source







All Articles