Search code examples
htmlgoogle-chromejquery-animateopera

Animate({right: 0}) not working properly in Chrome and Opera


I try to have an image slide from left to right using only jQuery and it works perfectly with .animate({right: 0}, 1500) on Firefox but not on Chrome and Opera (haven't tried other browsers though).

Here is a code example

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>Slide this squirrel</title>
    </head>
    <body>
        <div style="position:relative;margin:1%;padding:1%;border:1px solid black">
            <img id="squirrel" src="squirrel.jpg" alt="What a squirrel..." style="position:absolute;" />
        </div>
        <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
        <script>
          $(document).ready(function() {
            $("#squirrel").animate({right: 0}, 5000);
          });
        </script>
    </body>
</html>

Solution

  • You need to assign 100% to the right property for #squirrel in the CSS file.

    HTML:

    <div style="position:relative;margin:1%;padding:1%;border:1px solid black">
         <img id="squirrel" src="http://sweetclipart.com/multisite/sweetclipart/files/imagecache/middle/squirrel_2_line_art.png" height="80" width="100" style="position:absolute;" />
    </div>
    

    JS:

    $(document).ready(function() {
       $("#squirrel").animate({right: 0}, 5000);
    });
    

    CSS:

    #squirrel{
        right:100%;
    }
    

    I created an JSFiddle for you.

    URL: http://jsfiddle.net/m99bybnp/

    EDIT:

    I made a small change in the JS file.

    $(document).ready(function() {
        // We calculate the width which we need for the wanted displacement
        var width_Animate = $('#container_Squirrel').width() - $('#squirrel').width() ;
        $("#squirrel").animate({left: width_Animate}, 5000);
    });
    

    New JSFiddle URL: http://jsfiddle.net/m99bybnp/2/