0

Jquery. Is there a way to start an animation and stop that animation using the same button?

js:

   $('<div>').css({
        'width':'200px',
        'height':'200px',
        'background':'red'
    }).appendTo('body')
    $('<button>').appendTo('body').text('Click').click(function(){
        $('div').animate({
            'height': '250px'
        })
    })
    
    $('button').on('click',function(){
        $('div').animate({'height':'350px'})
    })
  • Look at this https://stackoverflow.com/a/931126/1225070 – Aefits May 27 '22 at 10:29
  • You can add/remove the class and text of the same button using jquery. – Santosh Aryal May 27 '22 at 10:30
  • 1
    A description of exactly what you're attempting to do here would help, as the code is quite confusing.You already have two event handlers on that button which make the div slide between 250px and 350px height. If you add another event handler to the button, how is it supposed to determine if you want to set the height to 250, 350, or stop the animation entirely? – Rory McCrossan May 27 '22 at 10:34
  • 1
    This *might* be what you're looking for: [how to check if an element is being animated](https://stackoverflow.com/questions/724911/how-do-i-find-out-with-jquery-if-an-element-is-being-animated): `if($(elem).is(':animated') ) {...}` – freedomn-m May 27 '22 at 10:51

1 Answers1

0

Look at this code;

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style type="text/css">
    div {
    background-color: #ffeecc;
    width: 100px;
    height: 100px;
    }
</style>
<script type="text/javascript">
    $(function () {
    var starts = false;

    $("#btnStart").click(function () {
        if (!starts) {
        start();
        } else {
        stop();
        }
    });

    function start() {
        starts = true;
        $("#btnStart").val("Stop");
        $("#divOne").animate(
        {
            width: "200px",
            height: "300px",
        },
        5000
        );
    }

    function stop() {
        starts = false;
        $("#btnStart").val("Start");
        $("#divOne").stop();
    }
    });
</script>
<input id="btnStart" type="button" value="Start" />
<br/><br/>
<div id="divOne" />