Zeitvertreib
Zeitvertreib

Reputation: 119

animate the removal and attaching of DOM elements

I want an interactive experience for my users.. AND I want to remain responsiveness. I try to learn the web by making a card game.

What I have is things to click on, which are supposed to be appearing somewhere else on the page. (Im using jQuery so far)

The (simplified) use-case is:

var card = $('[card=X]').remove();
$('.board').append(card);

Now I want to add some animation to it.

I am failing in choosing an appropriate framework. In the ones that I tried I couldn't time the removal, or the animation was gone, when I tried to call the removal, in a callback. Which was horrible, because the removal either fired before the callback or not at all. Or there was nothing left to be reattached.. So it should be more then just 'blur' or 'fade'.

So I want to detach a thing with an animation, place it somewhere else, and make it 'appear' there with an animation. As a superb bonus, those animations would have an orientation, so that the 'from' and 'where to' are visible appearing to the end user. (Like an arrow or a line drawn between those 2 locations.)

(Sry for not being more specific, but asking that question for all the frameworks/ libs out there appears not that appealing..)


edit: Nick pointed me in the right direction. My issue was the boilerplate code. I adjusted the code he provided. (added fade in animation + have the things 'reappearing' with event handler) ..thus I marked his answer as correct. (even that it wasn't, he didn't append the original thing, instead he created a new one.)

$('.cards ').on('click', '[card-id]', function() {
  $(this).fadeOut(1000, function() {
    var old = $(this).remove();

    $('.cards').append(old);
    old.fadeIn();
 });

Upvotes: 1

Views: 260

Answers (2)

NTR
NTR

Reputation: 1355

Consider using .animate() from Jquery. There is a lot you can do with it.

Take a look at the API: http://api.jquery.com/animate/

Upvotes: 1

Nick De Jaeger
Nick De Jaeger

Reputation: 1249

for(var i = 0; i < 6; i++) {
  $('.cards').append('<div class="card" card-id="'+i+'"></div>');
}


  $('[card-id]').click(function() {
    $(this).fadeOut(2000, function() {
      $(this).remove();
      
      $('.cards').append('<div class="card" card-id="'+$(this).attr('card-id')+'"></div>');
    });
  });
.card {
  position: relative;
  display: inline-block;
  width: 120px;
  height: 180px;
  background-color: #F4F4F4;
  border: 1px solid #E8E8E8;
  border-radius:5px;
  margin: 15px;
  cursor: pointer;
}
.card:after {
  content: attr(card-id);
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 24px;
  font-weight: 700;
  font-family: courier, serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="cards"></div>

Upvotes: 1

Related Questions