Yogi
Yogi

Reputation: 1579

How to animate the ajax/json response?

This is my piece of HTML code

<div class='qna_div'>
    <div class="q_div"></div>
    <div class="a_div"></div>
</div>

I make a Ajax request and get a json response for every click by the user and i append the q_div and a_div using the jquery function

$('.q_div').append(data.question);
$('.a_div').append(data.answer);

I have css keyframe animation on both q_div and a_div to come from right to left of the screen. But the animation works only on the first load of the page and not on the 'append' function for the json response. I am new to css and animations. help me out for the responsive animations

animation in css3 code:

.q_div {
    animation: q_ani 2s;
}

@keyframes q_ani {
    from{margin-left: 50px;}
    to{margin-left: default;}

}

Upvotes: 4

Views: 1378

Answers (4)

Felix Fong
Felix Fong

Reputation: 985

I hope it can help you,i just simple using the classList function and some SASS style rule

http://jsbin.com/vosuvam/2/edit?js,output

Upvotes: 0

Vanojx1
Vanojx1

Reputation: 5574

a possible solution using css animation

$(function() {
  var cssAnimationEnd = "webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend";
  $('.click').click(function() {
    $('.q_div, .a_div').addClass("animate").one(cssAnimationEnd , function() {
      $('.q_div, .a_div').removeClass("animate");
    });

  });
})
.q_div.animate {
  animation: q_ani 2s;
}
.a_div.animate {
  animation: q_ani 2s;
}
@keyframes q_ani {
  from {
    margin-left: 150%;
  }
  to {
    margin-left: default;
  }
}
/*for test purpose*/

.q_div,
.a_div {
  position: relative;
  height: 20px;
  width: 500px;
  background: #ddd;
  margin-top: 10px;
}
.qna_div {
  padding: 20px;
  width: 500px;
  background: #333;
}
body {
  overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click">go</button>
<div class='qna_div'>
  <div class="q_div"></div>
  <div class="a_div"></div>
</div>

Upvotes: 1

anmarti
anmarti

Reputation: 5143

You could use jquery to animate your divs. Put this code in the success ajax callback:

 // First put your divs to the right
 $('.q_div, .a_div').css('right','0');
 // Do the animation
 $('.q_div, .a_div').animate({
    left: 0,
 }, 1000);

https://jsfiddle.net/a8cq9yj1/1/

Upvotes: 0

Dmitry Yudin
Dmitry Yudin

Reputation: 978

You should delete and add .q_div class each time you need animation appear

Upvotes: 1

Related Questions