user4007301
user4007301

Reputation: 77

Animate moving of a td to another td

I use jquery to alter a table's td contents. I want to "move" the content of one td to another td, replacing the existing content.

E.g.:

| A | B |
| C | D |

now i "move the content of D to A" and get:

| D | B |
| C |     |

how can I animate this transition? Fade-out/fade-in is easy but how can one visually move D to A?

Thanks very much

Update: I need to do it programatically, so user drag/drop is not an option.

Upvotes: 2

Views: 2342

Answers (3)

David Hellsing
David Hellsing

Reputation: 108500

Here is one way:

  1. create a clone DIV and append the contents of the TD
  2. Position the clone above the TD D
  3. animate the clone to the A position
  4. empty A, append the clone contents and remove the clone

Something like this: (demo: http://jsfiddle.net/fvLr6z5s/)

var $d = $('.tdd')
var $a = $('.tda')
var offsetD = $d.offset()
var offsetA = $a.offset()
var $clone = $('<div>')
    .addClass('clone')
    .append($d.contents())
    .css(offsetD)
    .appendTo('body')
$clone.animate(offsetA, function() {
    $a.empty().append($clone.contents())
    $clone.remove()
})

Upvotes: 1

Shirin Abdolahi
Shirin Abdolahi

Reputation: 1067

you should move the <td> tags along.here I made you a jsfiddle

and here are my codes:

<table>
    <tr>
        <td id="moveto">A</td>
        <td>B</td>
    </tr>
     <tr>
        <td>C</td>
        <td id="movefrom">D</td>
    </tr>

</table>
<input type='button' id='change'value='change'>

Js

$(function() {
 $('#change').click(function(){
  $( "#movefrom" ).animate({
    left: "-=16",  //you should change this numbers based on your table size
    top: "-=22",
 }, 5000, function() {
// Animation complete.
 });

 });

});

Upvotes: 0

Luntegg
Luntegg

Reputation: 2556

You need wrapp your content in td in <div>, and get A and D cells absolut positions $(element).offset();, and with .animate() move it. After that you need remove hide div, and moved div replace in new cell.

$(function(){
    var posF = $('#first').offset();
    var posS = $('#second').offset();

    $('#second').css({
        position: 'absolute',
        top: posS.top, 
        left: posS.left
    });

    $('#first').fadeOut(function(){
         $(this).remove();   
    });

    $('#second').animate({
        top: posF.top, 
        left: posF.left
    }, 1000);
});

http://jsfiddle.net/9wa3vyh2/

Upvotes: 1

Related Questions