Return div to start position after animation?

3

How can I do to return my div to the starting position if it reaches a certain point on the left? I have the following current code:

$(document).ready(function() {   
    $("#botao").click(function() {      
        $(".maior").animate({left:"-=400px"},1000)
    });
});

CSS:

.maior {
    width: 1614px;
    height: 433px;
    float: right;
    position: absolute;
    font-family: "Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, sans-serif;
    color: #FFF;
    font-weight: bolder;
    overflow: hidden;
    left: 9px;
    top: -4px;
}
    
asked by anonymous 17.06.2014 / 19:18

2 answers

2

The jQuery property .animate() does nothing more than create a style attribute in your HTML element and change the its value gradually. So, if you remove this attribute after the animation, the element returns to its initial location.

You could do the following:

$(document).ready(function() {   
    $("#botao").click(function() {        
          $(".maior").animate({left:"-=400px"},1000,function(){
              $(this).removeAttr('style');
          });
    });
});

What I did above was to add a callback that fires whenever the animation ends, and within that callback I simply remove the style attribute of the element that was excited.

Example: FIDDLE

    
17.06.2014 / 19:35
1

You can use .stop () , this method has 2 parameters. The first is to clear the list of animations on hold, the second is to go to the end position. In your case, .stop(true, false);

You can use the complete function to check the end position, but you can also check at the beginning of the click (using .stop() ) and thus not run the animate, or change the value to its maximum on the left.

Tip (with many variables to be clearer:

$(document).ready(function () {
    $("#botao").click(function () {
        var maior = $(".maior");
        var limite = 200; // o seu valor limite aqui
        var posicao Atual = maior.position().left;
        var deslocamento = 400; // o deslocamento padrão
        if (posicao <= limite){ // caso esteja já no limite
            maior.stop(true, false);
            return;
        };
        // na linha de baixo verifica se o deslocamento padrão faz com que 
        // vá demasiado à esquerda, e nesse caso compensa o deslocamento
        if (posicao - 400 < limite) deslocamento = limite - posicao;
        maior.animate({
            left: "-=" + deslocamento + "px"
        }, 1000)
    });
});
    
17.06.2014 / 19:37