Search code examples
jquerycssjquery-animatemargin-left

Can't animate my div with margin left


I want to have an animation, with a timer that scroll my div with margin left, but I can't even have a proper animation, when I try on my website, it just instant get the "-margin" and on the test nothing. Can't even get an animation when I copy/paste a working code. I don't understand. Here is my code :

HTML:

<div id="twitter">
  <img style="width:50px;height:50px;" src="mypicture">
  <img id="next_tweet" src="mypicture">
  <img id="next_tweet" src="mypicture">

</div>
<script src="http://code.jquery.com/jquery-1.9.0rc1.js"></script>

CSS :

#twitter {
  width: 1000%;
  padding: 95px 0 0 400px;
  margin-left: 0px;
  height: 220px;
  -webkit-transition-delay: 2s;
  /* Safari */
  transition-delay: 2s;
}

#next_tweet {
  margin-left: 65px;
  width: 50px;
  height: 50px;
}

JavaScript :

jQuery(document).ready(

  function(){
            jQuery('#twitter').animate({
                marginLeft : "-1060px"
            },1000);

});

https://jsfiddle.net/sqs7btcx/1/

[just want my div going from right to left, all 5 secondes if possible]

if someone can help me, thanks


Solution

  • First of all, your code was not running on JSFiddle because it requires a https request to external files.

    Secondly, your CSS has a transition delay which was causing your animate function not to run correctly.

    JSFiddle

    $(document).ready(function() {
        $('#twitter').animate({
          marginLeft: "-=115px"
        }, 5000);
      });
    #twitter {
      width: 1000%;
      padding: 95px 0 0 400px;
      margin-left: 0px;
      height: 220px;
    }
    
    #next_tweet {
      margin-left: 65px;
      width: 50px;
      height: 50px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div id="twitter">
      <img style="width:50px;height:50px;" src="http://image.noelshack.com/fichiers/2015/10/1425504302-kancolle-9.png">
      <img id="next_tweet" src="http://image.noelshack.com/fichiers/2015/10/1425504302-kancolle-9.png">
      <img id="next_tweet" src="http://image.noelshack.com/fichiers/2015/10/1425504302-kancolle-9.png">
      <img id="next_tweet" src="http://image.noelshack.com/fichiers/2015/10/1425504302-kancolle-9.png">
      <img id="next_tweet" src="http://image.noelshack.com/fichiers/2015/10/1425504302-kancolle-9.png">
      <img id="next_tweet" src="http://image.noelshack.com/fichiers/2015/10/1425504302-kancolle-9.png">
    </div>