Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using one button to enable and stop a function rather than two buttons

I'm currently using two buttons (Go, Stop) to call and enable/disable my function. But is it possible to use one button to call the function to disable or enable. Example, clicking the button will make it blue, this enables the function, clicking the button again will make it go white, this disables the button.

My current code is:

<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>
like image 315
Casper Round Avatar asked May 31 '26 16:05

Casper Round


1 Answers

Sure, all you need is something to keep track of state, like a flag

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

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

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

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

FIDDLE

like image 112
adeneo Avatar answered Jun 02 '26 10:06

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!